//
//  EmailKeyWordItemsCell.swift
//  PhoneManager
//
//  Created by edy on 2025/5/12.
//

import UIKit

class EmailKeyWordItemsCell: UITableViewCell {

    static let id = "EmailKeyWordItemsCell"
    
    @IBOutlet weak var EmailFilterKeywordCollection: UICollectionView!
    @IBOutlet weak var collectionFlowLayout: EmailKeywordCollectionFlowLayout!
    @IBOutlet weak var collectHeightConstraint: NSLayoutConstraint!

    var callblock:(()->Void) = {}
    var datasoure:[String] = []
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.EmailFilterKeywordCollection.delegate = self
        self.EmailFilterKeywordCollection.dataSource = self;
        self.EmailFilterKeywordCollection.register(EmailKeywordCollectionCell.self, forCellWithReuseIdentifier: EmailKeywordCollectionCell.id)
        self.collectionFlowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
    }
    
    func reload() -> Void {
        self.layoutIfNeeded()
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            self.reloadItems()
        }
    }
    
    private func reloadItems() -> Void {
        self.EmailFilterKeywordCollection.reloadData()
        self.layoutIfNeeded()
        DispatchQueue.main.asyncAfter(deadline: .now()+0.05, execute: {
            if self.datasoure.count > 0 {
                self.collectHeightConstraint.constant = self.EmailFilterKeywordCollection.contentSize.height
            }else{
                self.collectHeightConstraint.constant = 0.0
            }
            self.layoutIfNeeded()
            DispatchQueue.main.asyncAfter(wallDeadline: .now() + 0.01) {
                let height = self.EmailFilterKeywordCollection.height
                Print("keywordCell: \(self.EmailFilterKeywordCollection.contentSize.height) height:\(height)")
                if height != self.EmailFilterKeywordCollection.contentSize.height {
                    if (self.datasoure.count == 0 && height <= 44) {
                        
                    }else{
                        self.callblock()
                    }
                }
            }
        })
    }
}

extension EmailKeyWordItemsCell : UICollectionViewDataSource,UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return datasoure.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmailKeywordCollectionCell.id, for: indexPath) as! EmailKeywordCollectionCell
        cell.titleL.text = datasoure[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        datasoure.remove(at: indexPath.row)
        EmailFilterManager.share.keyword = datasoure
        reloadItems()
        self.callblock()
    }
}
