//
//  MainSidebarMyProfileCollectionViewCell.swift
//  Tusker
//
//  Created by Shadowfacts on 4/30/22.
//  Copyright © 2022 Shadowfacts. All rights reserved.
//

import UIKit
import UserAccounts

class MainSidebarMyProfileCollectionViewCell: UICollectionViewListCell {
    
    private var verticalImageInset: CGFloat {
        if UIDevice.current.userInterfaceIdiom == .mac {
            return (28 - avatarImageSize) / 2
        } else {
            return (44 - avatarImageSize) / 2
        }
    }
    private var avatarImageSize: CGFloat {
        if UIDevice.current.userInterfaceIdiom == .mac {
            return 20
        } else {
            return 28
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        NotificationCenter.default.addObserver(self, selector: #selector(preferencesChanged), name: .preferencesChanged, object: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func updateUI(item: MainSidebarViewController.Item, account: UserAccountInfo) {
        var config = defaultContentConfiguration()
        config.text = item.title
        config.image = UIImage(systemName: item.imageName!)
        self.contentConfiguration = config
        if UIDevice.current.userInterfaceIdiom != .mac {
            let indicator = FastAccountSwitcherIndicatorView()
            // need to explicitly set the frame to get it vertically centered
            indicator.frame = CGRect(origin: .zero, size: indicator.intrinsicContentSize)
            accessories = [
                .customView(configuration: .init(customView: indicator, placement: .trailing()))
            ]
        }
        
        Task {
            await updateAvatar(account: account)
        }
    }
    
    private func updateAvatar(account: UserAccountInfo) async {
        let mastodonController = MastodonController.getForAccount(account)
        guard let account = try? await mastodonController.getOwnAccount(),
              let avatar = account.avatar else {
            return
        }
        _ = ImageCache.avatars.get(avatar, loadOriginal: false) { [weak self] _, image in
            guard let self = self,
                  let image = image else {
                      return
                  }
            
            DispatchQueue.main.async {
                guard var config = self.contentConfiguration as? UIListContentConfiguration else {
                    return
                }
                config.image = image
                config.directionalLayoutMargins.top = self.verticalImageInset
                config.directionalLayoutMargins.bottom = self.verticalImageInset
                config.imageProperties.maximumSize = CGSize(width: self.avatarImageSize, height: self.avatarImageSize)
                config.imageProperties.reservedLayoutSize = CGSize(width: UIListContentConfiguration.ImageProperties.standardDimension, height: 0)
                config.imageProperties.cornerRadius = Preferences.shared.avatarStyle.cornerRadiusFraction * self.avatarImageSize
                self.contentConfiguration = config
            }
        }
    }
    
    @objc private func preferencesChanged() {
        guard var config = self.contentConfiguration as? UIListContentConfiguration else {
            return
        }
        config.imageProperties.cornerRadius = Preferences.shared.avatarStyle.cornerRadiusFraction * avatarImageSize
        self.contentConfiguration = config
    }
    
}
