//
//  SettingViewController.swift
//  MpAccDemo
//

import UIKit
import MpAccSDK

class SettingViewController: UIViewController {
    
    @IBOutlet weak var configItemBtnsStackView: UIStackView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    func setupUI() -> Void {
        // 先清除
        self.configItemBtnsStackView.arrangedSubviews.forEach { view in
            self.configItemBtnsStackView.removeArrangedSubview(view)
            view.removeFromSuperview()
        }
        createSettingItemViews().forEach { itemView in
            self.configItemBtnsStackView.addArrangedSubview(itemView)
            if let parentView = self.configItemBtnsStackView.superview {
                parentView.addConstraint(itemView.widthAnchor.constraint(equalTo: parentView.widthAnchor, constant: -40))
            }
        }
    }
    
    @IBAction func resetConfig(_ sender: UIButton) {
        ConfigSetting.reset()
        setupUI()
    }
    
    @IBAction func cancelSetting(_ sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @IBAction func confirmSetting(_ sender: UIButton) {
        confirmSettingAction()
        self.navigationController?.popViewController(animated: true)
    }
}

extension SettingViewController {
    func session(title: String, @ViewsBuilder viewsBuilder: () -> [UIView]) -> [UIView] {
        let titleLabel = UILabel()
        titleLabel.text = title
        titleLabel.backgroundColor = .lightGray.withAlphaComponent(0.3)
        titleLabel.textAlignment = .center
        titleLabel.font = .systemFont(ofSize: 24)
        titleLabel.addConstraint(titleLabel.heightAnchor.constraint(equalToConstant: 40))
        let itemViews = viewsBuilder()
        return [titleLabel] + itemViews
    }
    func menuItemView(title: String = "", addEndView: Bool = false, @ViewsBuilder viewsBuilder: () -> [UIView], setup:(_ itemView: UIStackView) -> Void = {_ in}) -> UIStackView {
        var viewArr = [UIView]()
        if title.count > 0 {
            let lb = UILabel()
            lb.text = title + ":"
            lb.setContentCompressionResistancePriority(.required, for: .horizontal)
            lb.setContentHuggingPriority(.required, for: .horizontal)
            viewArr.append(lb)
        }
        viewArr.append(contentsOf: viewsBuilder())
        if addEndView {
            viewArr.append(UIView())
        }
        let sv = UIStackView(arrangedSubviews: viewArr)
        sv.distribution = .fill
        sv.alignment = .center
        sv.spacing = 10
        sv.addConstraint(sv.heightAnchor.constraint(greaterThanOrEqualToConstant: 50))
        setup(sv)
        return sv
    }
}
