//
//  FeaturedProfileCollectionViewCell.swift
//  Tusker
//
//  Created by Shadowfacts on 2/6/21.
//  Copyright © 2021 Shadowfacts. All rights reserved.
//

import UIKit
import Pachyderm

class FeaturedProfileCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var clippingView: UIView!
    @IBOutlet weak var headerImageView: UIImageView!
    @IBOutlet weak var avatarContainerView: UIView!
    @IBOutlet weak var avatarImageView: UIImageView!
    @IBOutlet weak var displayNameLabel: AccountDisplayNameLabel!
    @IBOutlet weak var noteTextView: StatusContentTextView!
    
    var account: Account?
    
    private var avatarRequest: ImageCache.Request?
    private var headerRequest: ImageCache.Request?
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        avatarContainerView.layer.cornerRadius = Preferences.shared.avatarStyle.cornerRadius(for: avatarContainerView)
        avatarContainerView.layer.cornerCurve = .continuous
        avatarImageView.layer.cornerRadius = Preferences.shared.avatarStyle.cornerRadius(for: avatarImageView)
        avatarImageView.layer.cornerCurve = .continuous
        
        displayNameLabel.font = UIFontMetrics(forTextStyle: .title1).scaledFont(for: .systemFont(ofSize: 20, weight: .semibold))
        displayNameLabel.adjustsFontForContentSizeCategory = true
        
        noteTextView.defaultFont = .preferredFont(forTextStyle: .body)
        noteTextView.monospaceFont = UIFontMetrics.default.scaledFont(for: .monospacedSystemFont(ofSize: 17, weight: .regular))
        noteTextView.adjustsFontForContentSizeCategory = true
        noteTextView.textContainer.lineBreakMode = .byTruncatingTail
        noteTextView.textContainerInset = UIEdgeInsets(top: 16, left: 4, bottom: 16, right: 4)
        
        backgroundColor = .clear
        clippingView.backgroundColor = .appBackground
        clippingView.layer.cornerRadius = 5
        clippingView.layer.cornerCurve = .continuous
        clippingView.layer.borderWidth = 1
        clippingView.layer.masksToBounds = true
        layer.shadowOpacity = 0.2
        layer.shadowRadius = 8
        layer.shadowOffset = .zero
        layer.masksToBounds = false
        updateLayerColors()
        
        NotificationCenter.default.addObserver(self, selector: #selector(preferencesChanged), name: .preferencesChanged, object: nil)
    }
    
    func updateUI(account: Account) {
        self.account = account
        
        displayNameLabel.updateForAccountDisplayName(account: account)
        
        noteTextView.setTextFromHtml(account.note)
        noteTextView.setEmojis(account.emojis, identifier: account.id)
        
        avatarImageView.image = nil
        if let avatar = account.avatar {
            avatarRequest = ImageCache.avatars.get(avatar) { [weak self] (_, image) in
                defer {
                    self?.avatarRequest = nil
                }
                guard let self = self,
                      let image = image,
                      self.account?.id == account.id else {
                    return
                }
                DispatchQueue.main.async {
                    self.avatarImageView.image = image
                }
            }
        }
        
        headerImageView.image = nil
        if let header = account.header {
            headerRequest = ImageCache.headers.get(header) { [weak self] (_, image) in
                defer {
                    self?.headerRequest = nil
                }
                guard let self = self,
                      let image = image,
                      self.account?.id == account.id else {
                    return
                }
                DispatchQueue.main.async {
                    self.headerImageView.image = image
                }
            }
        }
    }
    
    private func updateLayerColors() {
        if traitCollection.userInterfaceStyle == .dark {
            clippingView.layer.borderColor = UIColor.darkGray.withAlphaComponent(0.5).cgColor
            layer.shadowColor = UIColor.darkGray.cgColor
        } else {
            clippingView.layer.borderColor = UIColor.lightGray.withAlphaComponent(0.5).cgColor
            layer.shadowColor = UIColor.black.cgColor
        }
    }
    
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        updateLayerColors()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        layer.shadowPath = CGPath(roundedRect: bounds, cornerWidth: 5, cornerHeight: 5, transform: nil)
    }
    
    @objc private func preferencesChanged() {
        avatarContainerView.layer.cornerRadius = Preferences.shared.avatarStyle.cornerRadius(for: avatarContainerView)
        avatarImageView.layer.cornerRadius = Preferences.shared.avatarStyle.cornerRadius(for: avatarImageView)
        
        if let account = account {
            displayNameLabel.updateForAccountDisplayName(account: account)
        }
    }
    
    // MARK: Accessibility
    
    override var isAccessibilityElement: Bool {
        get { true }
        set {}
    }
    
    override var accessibilityAttributedLabel: NSAttributedString? {
        get {
            guard let account else {
                return nil
            }
            let s = NSMutableAttributedString(string: "\(account.displayNameWithoutCustomEmoji), ")
            s.append(noteTextView.attributedText)
            return s
        }
        set {}
    }
    
}
