//
//  EmojiLabel.swift
//  Tusker
//
//  Created by Shadowfacts on 3/1/20.
//  Copyright © 2020 Shadowfacts. All rights reserved.
//

import UIKit
import Pachyderm

class EmojiLabel: UILabel, BaseEmojiLabel {
    
    private(set) var hasEmojis = false
    
    var emojiIdentifier: AnyHashable?
    var emojiRequests: [ImageCache.Request] = []
    var emojiFont: UIFont { font }
    var emojiTextColor: UIColor { textColor }
    
    func setEmojis<ID: Hashable>(_ emojis: [Emoji], identifier: ID?) {
        guard emojis.count > 0, let attributedText = attributedText else { return }

        replaceEmojis(in: attributedText, emojis: emojis, identifier: identifier) { [weak self] (newAttributedText, didReplaceEmojis) in
            guard let self = self, self.emojiIdentifier == AnyHashable(identifier) else { return }
            self.hasEmojis = didReplaceEmojis
            self.attributedText = newAttributedText
            self.setNeedsLayout()
            self.setNeedsDisplay()
        }
    }
    
    func removeEmojis() {
        emojiIdentifier = nil
        emojiRequests.forEach { $0.cancel() }
        emojiRequests = []
        hasEmojis = false
    }
    
}
