//
//  AccountTableViewCell.swift
//  Tusker
//
//  Created by Shadowfacts on 9/5/19.
//  Copyright © 2019 Shadowfacts. All rights reserved.
//

import UIKit
import SwiftSoup

class AccountTableViewCell: UITableViewCell {

    weak var delegate: (TuskerNavigationDelegate & MenuActionProvider)?
    var mastodonController: MastodonController! { delegate?.apiController }
    
    @IBOutlet weak var avatarImageView: UIImageView!
    @IBOutlet weak var displayNameLabel: AccountDisplayNameLabel!
    @IBOutlet weak var usernameLabel: UILabel!
    @IBOutlet weak var noteLabel: EmojiLabel!
    
    var accountID: String!
    
    private var avatarRequest: ImageCache.Request?
    private var isGrayscale = false
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        avatarImageView.layer.masksToBounds = true
        avatarImageView.layer.cornerCurve = .continuous
        
        usernameLabel.font = UIFontMetrics(forTextStyle: .body).scaledFont(for: .systemFont(ofSize: 15, weight: .light))
        usernameLabel.adjustsFontForContentSizeCategory = true
        
        noteLabel.font = UIFontMetrics(forTextStyle: .body).scaledFont(for: .systemFont(ofSize: 15))
        noteLabel.adjustsFontForContentSizeCategory = true

        NotificationCenter.default.addObserver(self, selector: #selector(updateUIForPrefrences), name: .preferencesChanged, object: nil)
    }
    
    @objc func updateUIForPrefrences() {
        avatarImageView.layer.cornerRadius = Preferences.shared.avatarStyle.cornerRadius(for: avatarImageView)
        
        guard let account = mastodonController.persistentContainer.account(for: accountID) else {
            // this table view cell could be cached in a table view (e.g., SearchResultsViewController) for an account that's since been purged
            return
        }
        displayNameLabel.updateForAccountDisplayName(account: account)
        
        if isGrayscale != Preferences.shared.grayscaleImages {
            updateGrayscaleableUI(account: account)
        }
    }
    
    func updateUI(accountID: String) {
        self.accountID = accountID
        guard let account = mastodonController.persistentContainer.account(for: accountID) else {
            fatalError("Missing cached account \(accountID)")
        }
        
        usernameLabel.text = "@\(account.acct)"
        
        updateGrayscaleableUI(account: account)
        updateUIForPrefrences()
    }
    
    private func updateGrayscaleableUI(account: AccountMO) {
        isGrayscale = Preferences.shared.grayscaleImages
        
        let accountID = self.accountID
        
        avatarImageView.image = nil
        if let avatarURL = account.avatar {
            avatarRequest = ImageCache.avatars.get(avatarURL) { [weak self] (_, image) in
                guard let self = self else { return }
                self.avatarRequest = nil
                
                guard let image = image,
                      self.accountID == accountID,
                      let transformedImage = ImageGrayscalifier.convertIfNecessary(url: avatarURL, image: image) else { return }
                
                DispatchQueue.main.async {
                    self.avatarImageView.image = transformedImage
                }
            }
        }
        
        let doc = try! SwiftSoup.parse(account.note)
        noteLabel.text = try! doc.text()
        noteLabel.setEmojis(account.emojis, identifier: account.id)
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
        
        avatarRequest?.cancel()
    }

}

extension AccountTableViewCell: SelectableTableViewCell {
    func didSelectCell() {
        delegate?.selected(account: accountID)
    }
}

extension AccountTableViewCell: MenuPreviewProvider {
    func getPreviewProviders(for location: CGPoint, sourceViewController: UIViewController) -> PreviewProviders? {
        guard let mastodonController = mastodonController else { return nil }
        return (
			content: { ProfileViewController(accountID: self.accountID, mastodonController: mastodonController) },
            actions: { self.delegate?.actionsForProfile(accountID: self.accountID, source: .view(self.avatarImageView)) ?? [] }
		)
    }
}

extension AccountTableViewCell: DraggableTableViewCell {
    func dragItemsForBeginning(session: UIDragSession) -> [UIDragItem] {
        guard let account = mastodonController.persistentContainer.account(for: accountID),
              let currentAccountID = mastodonController.accountInfo?.id else {
            return []
        }
        let provider = NSItemProvider(object: account.url as NSURL)
        let activity = UserActivityManager.showProfileActivity(id: account.id, accountID: currentAccountID)
        activity.displaysAuxiliaryScene = true
        provider.registerObject(activity, visibility: .all)
        return [UIDragItem(itemProvider: provider)]
    }
}
