//
//  KMAdvertisementTableView.swift
//  KMAdvertisement
//
//  Created by lizhe on 2022/11/28.
//

#if os(OSX)
    import AppKit
#elseif os(iOS)
    import UIKit
#endif
@objcMembers open class KMAdvertisementTableView: KMAdvertisementBaseView {

    @IBOutlet var contentView: NSView!
    
    @IBOutlet weak var collectionView: NSCollectionView!
    lazy var presenter: KMAdvertisementTableViewPresenter! = KMAdvertisementTableViewPresenter()

    /**
      @abstract 外部传入数据
      @param inputData 文件路劲
      */
    open var inputData: KMAdvertisementModel! {
        didSet {
            self.presenter.initPresenter(view: self, data: inputData)
        }
    }

    //内部使用数据
    fileprivate var data: [KMAdvertisementModelSection]?

    open override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        // Drawing code here.
    }
    
    convenience init (data: KMAdvertisementModel, superView: NSView) {
        self.init(frame: superView.bounds)
        self.presenter.initPresenter(view: self, data: data)
        superView.addSubview(self)
        self.autoresizingMask = [.height , .width]
//        self.translatesAutoresizingMaskIntoConstraints = false
//        NSLayoutConstraint.activate([
//            self.topAnchor.constraint(equalTo: topAnchor),
//            self.leftAnchor.constraint(equalTo: leftAnchor),
//            self.rightAnchor.constraint(equalTo: rightAnchor),
//            self.bottomAnchor.constraint(equalTo: bottomAnchor)])
//        self.updateConstraintsForSubtreeIfNeeded()
    }
    
    public override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        initContentView()
        setup()
    }
    
    // MARK: 初始化
    public required init?(coder decoder: NSCoder) {
        super.init(coder: decoder)
        initContentView()
        setup()
    }

    private func initContentView() {
        //绑定xib
        let resource = NSNib(nibNamed: String(describing: self.classForCoder.self),
                             bundle: Bundle(for: self.classForCoder.self))!
        resource.instantiate(withOwner: self, topLevelObjects: nil)
        addSubview(contentView)
        contentView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            contentView.topAnchor.constraint(equalTo: topAnchor),
            contentView.leftAnchor.constraint(equalTo: leftAnchor),
            contentView.rightAnchor.constraint(equalTo: rightAnchor),
            contentView.bottomAnchor.constraint(equalTo: bottomAnchor)])
        contentView.updateConstraintsForSubtreeIfNeeded()
    }
    
    func setup() {
        //设置代理
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        //是否可选中
        self.collectionView.isSelectable = true
        //注册cell
        self.collectionView.register(KMAdvertisementCollectionViewItem.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMAdvertisementCollectionViewItem"))
    }
}

extension KMAdvertisementTableView: KMAdvertisementTableViewPresenterDelegate {
    func showData(presenter: KMAdvertisementTableViewPresenter, data: Array<KMAdvertisementModelSection>) {
        self.data = data
        self.collectionView.reloadData()
    }
}

extension KMAdvertisementTableView: NSCollectionViewDelegate {
    //当item被选中
    public func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
        print("点击")
        let view = collectionView.item(at: indexPaths.first!) as! KMAdvertisementCollectionViewItem
        
        var content = view.model
        if actionCompletion != nil {
            content?.index = indexPaths.first?.item
            actionCompletion!(.tap, content!)
        }
    }
    
   //当item取消选中
    public func collectionView(_ collectionView: NSCollectionView, didDeselectItemsAt indexPaths: Set<IndexPath>) {
        let view = collectionView.item(at: indexPaths.first!) as! KMAdvertisementCollectionViewItem
    }
}

extension KMAdvertisementTableView: NSCollectionViewDataSource {
    public func numberOfSections(in collectionView: NSCollectionView) -> Int {
        return self.data?.count ?? 0
    }
    
    public func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
        let model: KMAdvertisementModelSection = (self.data?[section])!
        return model.content!.count
    }
    
    //返回对应的item自定义个体
    public func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
        let view = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KMAdvertisementCollectionViewItem"), for: indexPath) as! KMAdvertisementCollectionViewItem
        
        let model = self.data?[indexPath.section]
        view.model = model?.content![indexPath.item]
        return view
    }
    
    public func collectionView(_ collectionView: NSCollectionView, viewForSupplementaryElementOfKind kind: NSCollectionView.SupplementaryElementKind, at indexPath: IndexPath) -> NSView {
        var nibName: String?
        if kind == NSCollectionView.elementKindSectionHeader {
            nibName = "KMAdvertisementCollectionHeadView"
        }
        
        let view = collectionView.makeSupplementaryView(ofKind: kind, withIdentifier: NSUserInterfaceItemIdentifier(rawValue: nibName!), for: indexPath)
        if let view = view as? KMAdvertisementCollectionHeadView {
            let model = self.data?[indexPath.section]
            view.model = model
        }
        return view
    }
}

extension KMAdvertisementTableView: NSCollectionViewDelegateFlowLayout {
    
    public func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
        return NSSize(width: self.contentView.bounds.width, height: 32)
    }
    
    public func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> NSSize {
        return NSSize(width: 0, height: 30)
    }
    
    public func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 4
    }
}
