//
//  Tags.swift
//  MVMCoreUI
//
//  Created by Dhamodaram Nandi on 27/05/20.
//  Copyright © 2020 Verizon Wireless. All rights reserved.
//

import Foundation

open class Tags: View, MFButtonProtocol {
    public var collectionView: CollectionView!
    public var collectionViewHeight: NSLayoutConstraint!
    private var tagsListModel: TagsModel? {
        return model as? TagsModel
    }
    
    private var delegateObject: MVMCoreUIDelegateObject?
    
    /// The models for the molecules.
    public var tags: [TagModel]?
    
    open override func layoutSubviews() {
        super.layoutSubviews()
        // Accounts for any collection size changes
        DispatchQueue.main.async {
            self.collectionView.collectionViewLayout.invalidateLayout()
            self.collectionViewHeight.constant = self.collectionView.contentSize.height
            self.delegateObject?.moleculeDelegate?.moleculeLayoutUpdated(self)
        }
    }
    
    // MARK: - MVMCoreViewProtocol
    open override func setupView() {
        super.setupView()
        collectionView = createCollectionView()
        addSubview(collectionView)
        NSLayoutConstraint.constraintPinSubview(toSuperview: collectionView)
        collectionViewHeight = collectionView.heightAnchor.constraint(equalToConstant: 300)
        collectionViewHeight?.isActive = true
    }
    
    // MARK: - MoleculeViewProtocol
    open override func set(with model: MoleculeModelProtocol, _ delegateObject: MVMCoreUIDelegateObject?, _ additionalData: [AnyHashable: Any]?) {
        super.set(with: model, delegateObject, additionalData)
        self.delegateObject = delegateObject
        guard let tagsListModel = model as? TagsModel else { return }
        tags = tagsListModel.tags
        registerCells()
        collectionView.reloadData()
    }
    
    @objc override open func updateView(_ size: CGFloat) {
        super.updateView(size)
        collectionView.updateView(size)
    }
    
    // MARK: - Creation
    /// Creates the layout for the collection.
    open func createCollectionViewLayout() -> UICollectionViewLayout {
        let layout = UICollectionViewLeftAlignedLayout()
        layout.estimatedItemSize = CGSize(width: 140, height: 40)
        layout.minimumLineSpacing = 24.0
        layout.minimumInteritemSpacing = 12.0
        return layout
    }
    
    /// Creates the collection view.
    open func createCollectionView() -> CollectionView {
        let collection = CollectionView(frame: .zero, collectionViewLayout: createCollectionViewLayout())
        collection.dataSource = self
        collection.delegate = self
        return collection
    }
    
    /// Registers the cells with the collection view
    open func registerCells() {
        collectionView.register(TagCollectionViewCell.self, forCellWithReuseIdentifier: "TagCollectionViewCell")
    }
}

extension Tags: UICollectionViewDataSource {
    open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return tags?.count ?? 0
    }
    
    open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let molecule = tags?[indexPath.row],
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TagCollectionViewCell", for: indexPath) as? TagCollectionViewCell else {
                fatalError()
        }
        cell.reset()
        cell.set(with: molecule, delegateObject, nil)
        cell.layoutIfNeeded()
        return cell
    }
}

extension Tags: UICollectionViewDelegate {
    open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let tagModel = tags?[indexPath.row],
            let tagAction = tagModel.action else { return }
        Button.performButtonAction(with: tagAction, button: self, delegateObject: delegateObject, additionalData: nil)
    }
}
