//
//  FilterCheckBox.swift
//  Productz
//
//  Created by Amine  on 11/8/20.
//  Copyright © 2020 Amine. All rights reserved.
//

import UIKit
import RealmSwift


protocol FilterCheckBoxDelegate {
    func onClicked(current: String,selected_items: [Int])
}

class FilterCheckBox: UIView {
    
    var current: String? = nil
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var stackView: UIStackView!
    
    var isMultiple = false
    var style = RadioBoxStyle()
    private var items: [Int: UIButton] = [:]
    private var selected: [Int] = []
    var delegate: FilterCheckBoxDelegate? = nil
    
    
    func setup(items: [FilterObjStruct], style: RadioBoxStyle ) {
        
        self.items = [:]
        self.selected = []
       
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.contentInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
        
        stackView.removeAllArrangedSubviews()
        
        //setup style
        self.style = style
        
        for val in items{
            
            let b1 = createView(size: 40, key: val.title, id: val.id,active: false)
            stackView.addArrangedSubview(b1)
            
        }
        
             
    }
    
    func setup(items: [FilterObjStruct] ) {
        
        self.items = [:]
        self.selected = []
       
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.contentInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
        
        stackView.removeAllArrangedSubviews()
        
        //setup style
        /*self.style = RadioBoxStyle()
        self.style.disabledBorder = .lightGray
        self.style.disabledBackground = Colors.white
        self.style.disabledText = .lightGray
        self.style.enabledBorder = Colors.primaryColor
        self.style.enabledBackground = Colors.primaryColor
        self.style.enabledText = .white*/
        
        
        self.style.disabledBorder = .lightGray
        self.style.disabledBackground = Colors.white
        self.style.disabledText = .lightGray
               
        self.style.enabledBorder = Colors.primaryColor
        self.style.enabledBackground = Colors.white
        self.style.enabledText = Colors.primaryColor
        
        
        
        for val in items{
            
            let b1 = createView(size: 40, key: val.title, id: val.id,active: false)
            stackView.addArrangedSubview(b1)
            
        }
        
             
    }
    
    func setup(items: Results<FilterObject> ) {
        
        self.items = [:]
        self.selected = []
       
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.contentInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
        
        stackView.removeAllArrangedSubviews()
        
        //setup style
        /*self.style = RadioBoxStyle()
        self.style.disabledBorder = .lightGray
        self.style.disabledBackground = Colors.white
        self.style.disabledText = .lightGray
        self.style.enabledBorder = Colors.primaryColor
        self.style.enabledBackground = Colors.primaryColor
        self.style.enabledText = .white*/
        
        
        self.style.disabledBorder = .lightGray
        self.style.disabledBackground = Colors.white
        self.style.disabledText = .lightGray
               
        self.style.enabledBorder = Colors.primaryColor
        self.style.enabledBackground = Colors.gray
        self.style.enabledText = Colors.primaryColor
        
        
        
        for val in items{
            
            let b1 = createView(size: 40, key: val.title, id: val.id,active: false)
            stackView.addArrangedSubview(b1)
            
        }
        
             
    }
    
    
    
    
    func createView(size: CGFloat,key:String, id: Int, active: Bool) -> UIView {
        
        let view = UIView()
        view.backgroundColor  = .clear
        //view.layer.cornerRadius = 8
        view.translatesAutoresizingMaskIntoConstraints = false

        let button = UIButton()
        button.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(button)
        button.setTitle("    "+key.localized.uppercased()+"    ", for: .normal)
       
        let constraints = [
            button.topAnchor.constraint(equalTo: view.topAnchor, constant: 0),
            button.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0),
            button.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0),
            button.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0),
        ]
        
        
        
        button.initDefaultFont(size: 12)
        button.setTitleColor(style.disabledText, for: .normal)
        
        self.items[id] = button
    
        desactive(view: button)
        
        NSLayoutConstraint.activate(constraints)

        view.heightAnchor.constraint(equalToConstant: size).isActive = true
        
        button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
        
        return view
    }
    
    
    func toggle(id: Int){
        
        for (_id,button) in self.items{
            
            if _id == id && selected.contains(id){ // is active
                
                desactive(view: button)
                
                if let index = selected.firstIndex(of: id) {
                    selected.remove(at: index)
                }
                
            }else if _id == id && !selected.contains(id){ // is inactive
                
                active(view: button)
                selected.append(id)
                
            }
        }
        
    }
    
    @objc func buttonClicked(sender : UIButton){
        
        
        if !isMultiple{
            
            for (id,button) in self.items{
                if sender != button{
                    desactive(view: button)
                    if let index = selected.firstIndex(of: id) {
                        selected.remove(at: index)
                    }
                }
            }
            
        }
       
        for (id,button) in self.items{
            
            if sender == button && selected.contains(id){ // is active
                
                desactive(view: button)
                
                if let index = selected.firstIndex(of: id) {
                    selected.remove(at: index)
                }
                
            }else if sender == button && !selected.contains(id){ // is inactive
                
                active(view: button)
                selected.append(id)
                
            }
        }
        
        if let del = delegate{
            del.onClicked(current: self.current!, selected_items: selected)
        }
        
    }
    
    private func active(view: UIButton){
       
        
        view.backgroundColor = style.enabledBackground
        view.layer.cornerRadius = 5
        view.layer.borderWidth = 1
        view.layer.borderColor = style.enabledBorder?.cgColor
        view.setTitleColor(style.enabledText, for: .normal)
        view.backgroundColor = style.enabledBackground
        
        /*UIView.animate(withDuration: 0.3, animations: {
           self.layoutIfNeeded()
        })*/
    }
    
    private func desactive(view: UIButton){
        
        view.backgroundColor = style.disabledBackground
        view.layer.cornerRadius = 5
        view.layer.borderWidth = 1
        view.layer.borderColor = style.disabledBorder?.cgColor
        view.setTitleColor(style.disabledText, for: .normal)
        view.backgroundColor = style.disabledBackground
        
        /*UIView.animate(withDuration: 0.3, animations: {
            
            
            self.layoutIfNeeded()
        })*/
    }
    
}
