//
//  ConfigItemViewProtocol.swift
//  MpAccDemo
//
//  Created by Robin on 2023/10/16.
//

import UIKit

protocol ConfigItemViewProtocol: UIView {
    var currentItem: MpItem! { get set }
    var itemList: [MpItem]! { get set }
    var saveBlock: ((MpItem) -> Void)? { get set }
    var changedBlock: ((MpItem) -> Void)? { get set }
    
    func currentItemDidChanged() -> Void
    func itemListChanged() -> Void
    
    static func newItem() -> ConfigItemViewProtocol
}

extension ConfigItemViewProtocol {
    
    func updateCurrentItem(_ item: MpItem) -> Void {
        self.currentItem = item
        currentItemDidChanged()
        if let changedBlock {
            changedBlock(item)
        }
    }
    
    func updateConfig() {
        guard let item = self.currentItem else { return }
        self.saveBlock?(item)
    }
    
    static func newItem(@ItemBuilder itemsBuilder: () -> [MpItem]) -> ConfigItemViewProtocol {
        let itemView = newItem()
        let items = itemsBuilder()
        itemView.itemList = items
        itemView.itemListChanged()
        if let selectedItem = items.first(where: { $0.on }) {
            itemView.updateCurrentItem(selectedItem)
        } else if let firstItem = items.first {
            itemView.updateCurrentItem(firstItem)
        } else {
            assertionFailure("至少需要一个配置项")
        }
        return itemView
    }
    
    func save(_ block: @escaping (_ item:MpItem) -> Void) -> ConfigItemViewProtocol {
        self.saveBlock = block
        return self
    }
    
    func changed(_ block: @escaping (_ item:MpItem) -> Void) -> ConfigItemViewProtocol {
        self.changedBlock = block
        return self
    }
    
    func setting( _ block: (_ itemView: ConfigItemViewProtocol) -> Void) -> ConfigItemViewProtocol {
        block(self)
        return self
    }
}

@resultBuilder
struct ViewsBuilder {
    static func buildBlock(_ items: UIView...) -> [UIView] {
        return items
    }
    static func buildArray(_ components: [[UIView]]) -> [UIView] {
        components.flatMap({ $0 })
    }
    static func buildBlock(_ components: [UIView]) -> [UIView] {
        return components
    }
    static func buildEither(first component: [UIView]) -> [UIView] {
        component
    }
    static func buildEither(second component: [UIView]) -> [UIView] {
        component
    }
}
