//
//  MultiSourceEmojiLabel.swift
//  Tusker
//
//  Created by Shadowfacts on 10/18/20.
//  Copyright © 2020 Shadowfacts. All rights reserved.
//

import UIKit
import Pachyderm

private let emojiRegex = try! NSRegularExpression(pattern: ":(\\w+):", options: [])

class MultiSourceEmojiLabel: UILabel, BaseEmojiLabel {
    var emojiIdentifier: AnyHashable?
    var emojiRequests = [ImageCache.Request]()
    var emojiFont: UIFont { font }
    var emojiTextColor: UIColor { textColor }
    
    var combiner: (([NSAttributedString]) -> NSAttributedString)?
    
    func setEmojis<ID: Hashable>(pairs: [(String, [Emoji])], identifier: ID) {
        guard pairs.count > 0 else { return }
        
        var attributedStrings = pairs.map { NSAttributedString(string: $0.0) }
        
        let recombine = { [weak self] in
            if let self,
               let combiner = self.combiner {
                self.attributedText = combiner(attributedStrings)
            }
        }
        recombine()
        
        for (index, (string, emojis)) in pairs.enumerated() {
            self.replaceEmojis(in: string, emojis: emojis, identifier: identifier) { (attributedString, _) in
                attributedStrings[index] = attributedString
                DispatchQueue.main.async(execute: recombine)
            }
        }
    }

}
