//
//  NSelectableView.swift
//  TTBaseView
//
//  Created by MnzfM on 29.08.2019.
//  Copyright © 2019 MnzfM. All rights reserved.
//

import UIKit

public protocol NSelectableViewDelegate: NSObject {
    func willPresentSelectionList(selectableView: NSelectableView) -> Void
    func didPresentSelectionList(selectableView: NSelectableView) -> Void
    func didSelectedItem(selectableView: NSelectableView,selectedObj:KeyValueObject) -> Void
    func didClearFilter(selectableView: NSelectableView) -> Void
}

public extension NSelectableViewDelegate {
    
    func willPresentSelectionList(selectableView: NSelectableView) -> Void {

    }
    
    func didPresentSelectionList(selectableView: NSelectableView) -> Void {
        
    }
    
    func didClearFilter(selectableView: NSelectableView) -> Void {
        
    }
}

@IBDesignable open class NSelectableView: UIView {
    
    @IBOutlet weak var lblTitle: UILabel!
    @IBOutlet weak var btnSelect: UIButton!
    @IBOutlet weak var imageView: UIImageView!
    
    @IBOutlet weak var btnLeadingFullView: NSLayoutConstraint!
    @IBOutlet weak var btnLeadingTitle: NSLayoutConstraint!
    
    public weak var delegate: NSelectableViewDelegate?
    
    public var complitionHandler: ((UIButton)->())?
    
    var source = [KeyValueObject]()
    var selectedObj = KeyValueObject()
    var showListType = NSelectableShowType.showValue
    var showReturnType = NSelectableShowType.showValue
    var defaultValue = ""
    var showClearBtn = false

    
    open var didSelectedItemHandler: ((KeyValueObject) -> ())? // açılır penceredeki table didselect item yapılınca tetiklenir.
    open var didClearFilterHandler:(()->())? // Filtre temizlendiği zaman bu tetiklenir.

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.commonInitialization()
    }
    
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder:aDecoder)
        self.commonInitialization()
    }
    
    func commonInitialization()  {
        let bundle = Bundle(for: self.classForCoder)
        let view = bundle.loadNibNamed("NSelectableView", owner: self, options: nil)?.first as! UIView
        view.frame = self.bounds
        self.addSubview(view)
        btnSelect.layer.cornerRadius = 5
        btnSelect.layer.borderWidth = 1
        btnSelect.layer.borderColor = UIColor.white.cgColor
        btnSelect.contentEdgeInsets.left = 10
    }
   
    // Select butonu clicked fonksiyonu
    @IBAction func btnClicked(_ sender: UIButton) {
        if let complition = complitionHandler {
            complition(sender)
        }
        else{
            openListView()
        }
    }
    
    open func openListView(){
        let bundle = Bundle(for: self.classForCoder)
        let nSelectedDetailVC = NSelectableViewDetail(nibName: "NSelectableViewDetail", bundle: bundle)
        nSelectedDetailVC.modalPresentationStyle = .overCurrentContext
        nSelectedDetailVC.source = self.source
        nSelectedDetailVC.selectedParent = self
        self.delegate?.willPresentSelectionList(selectableView: self)
        UIApplication.topViewController()?.present(nSelectedDetailVC, animated: false, completion: {
            self.delegate?.didPresentSelectionList(selectableView: self)
        })
    }
    
    //gösterim type full alan olması isteniliyorsa
    open func fullButton(){
        btnLeadingTitle.priority = .defaultLow
        btnLeadingFullView.priority = .required
        lblTitle.isHidden = true
    }
    
    //Gösterilecek datalar burada set ediliyor. ya obje array  ya da  string array gönderilir.
    open func setSourceObjects<T>(objectArray:[T],
                                  key:KeyPath<T, String>,
                                  value:KeyPath<T, String>){
        
        source = objectArray.compactMap { KeyValueObject(key: $0[keyPath:key], value: $0[keyPath:value], obj: $0 as AnyObject) }
   
    }
    
    open func setSourceString(stringArray:[String]){
        
        source = stringArray.compactMap { KeyValueObject.init(key: "", value: $0, obj: $0 as AnyObject) }
    }
    
    open func setSourceKV(sourceKV:[KeyValueObject]){
        
        self.source = sourceKV
    }
    
    
    
    // Default gösterilecek data için bu fonksiyon kullanılır.
    open func setSelectedValue(showValue:String){
        
        self.selectedObj = KeyValueObject(key: "", value: showValue, obj: nil)
        
        switch showReturnType {
        case .showKey: self.selectedObj = KeyValueObject(key: showValue, value: "",obj: nil)
        case .showValue: self.selectedObj = KeyValueObject(key: "", value: showValue,obj: nil)
        case .showKeyValue: self.selectedObj = KeyValueObject(key: "", value: showValue,obj: nil)
        }
        
        self.setSelectedObjName()
    }
    
    // select butonu yanındaki label yazısı için kullanılır.
    open func setTitle(title:String){
        self.lblTitle.text = title
    }
    
    open func setTitleColor(_ color: UIColor ){
        self.lblTitle.textColor = color
        btnSelect.setTitleColor(color, for: .normal)
        btnSelect.layer.borderWidth = 1
        btnSelect.layer.borderColor = color.cgColor
        imageView.tintColor = color
    }
    
    func setSelectedObjName() { // table den seçilince bu fonksiyon çagrılıyor
        
        switch showReturnType {
        case .showKey: btnSelect.setTitle(selectedObj.key == "" ? defaultValue:selectedObj.key, for: .normal)
        case .showValue: btnSelect.setTitle(selectedObj.value == "" ? defaultValue:selectedObj.value, for: .normal)
        case .showKeyValue: btnSelect.setTitle(selectedObj.key == "" ? defaultValue: (selectedObj.key + "-" + selectedObj.value), for: .normal)
        }
    }
    
    func setDefaultTitle() {
        
        btnSelect.setTitle(defaultValue, for: .normal)
    }
    
    open func getSelectedObj() -> KeyValueObject{
        
        return selectedObj
    }
    
    public func setInitValue(title:String, buttonText:String, defaultValue:String, isEditibleBtn:Bool, showClearBtn:Bool = false){
        
        self.lblTitle.text = title
        self.defaultValue = defaultValue
        btnSelect.isEnabled = isEditibleBtn
        self.showClearBtn = showClearBtn
        setSelectedValue(showValue: buttonText)
        
    }
    
    public func setEditible(status:Bool) {
        
        btnSelect.isEnabled = status
    }
    
    public func setShowType(showListType:NSelectableShowType, showReturnType:NSelectableShowType) {
        
        self.showListType = showListType
        self.showReturnType = showReturnType
        self.setSelectedValue(showValue: btnSelect.title(for: .normal) ?? defaultValue)
    }
    
    public func getSourceCount() -> Int{
        
        return self.source.count
    }
    

}



//       let deneme2 = MyReftectance(key: "2.", value: "2. eleman")
//       let source = [deneme1,deneme2]
//
//       getParameterName(source, key: \MyReftectance.a1, value: \MyReftectance.b1)



//self.nsAcSelected.selectedClosure = {(item) in
//
//    // burada obje seçildigindeki tetiklenen fonksiyon kullanımı
//}








// herhangi bir viewcontrollerda bir ekran açma
// herhangi 2 objenin maplenmesi
