//
//  ProductSearch.swift
//  NearbyStores
//
//  Created by Amine  on 8/21/19.
//  Copyright © 2019 Amine. All rights reserved.
//

import Foundation
import UIKit
import SkyFloatingLabelTextField
import RealmSwift
import SwiftRangeSlider


class ProductSearch: MySearchView, UITextFieldDelegate , RadioBoxDelegate, FilterCheckBoxDelegate{
    
    var ex_parameters: [String: String] = [
           "__req_category": "0",
           "__req_redius": String(AppConfig.distanceMaxValue),
           "__req_list_order": String(ListProductView.Request.nearby),
           "__req_search": "",
       ]
    
    //variables
    var isDiscountType = false
    var isPriceType = false
    var priceRangeSelected = ""
    var discountRangeSelected = ""
    

    @IBOutlet weak var stackView: UIStackView!
    @IBOutlet weak var category_label: UILabel!
    @IBOutlet weak var search_field: SkyFloatingLabelTextField!
    
    @IBOutlet weak var radius_label: UILabel!
    @IBOutlet weak var sliderView: UISlider!
    
  
    @IBOutlet weak var category_container: UIView!
    
    @IBAction func radiusSlide(_ sender: Any) {
        
        let slider: UISlider = sender as! UISlider
        let value = Int(slider.value)
        
        if value < 100  {
            radius_label.text = "\("Radius".localized) \(value) \(AppConfig.distanceUnit.localized)"
        }else{
            radius_label.text = "\("Radius".localized) +\(value) \(AppConfig.distanceUnit.localized)"
        }
        
    }
    
    @IBOutlet weak var range_slary_label: UILabel!
    @IBOutlet weak var rangeSlider_Salary_View: RangeSlider!
    
    @IBAction func rangeSlider_SalaryAction(_ sender: Any) {
        
        let slider: RangeSlider = sender as! RangeSlider
        let valueMin = Int(slider.lowerValue)
        let valueMax = Int(slider.upperValue)
        
        if let c  = currency?.getValue(defaultValue: "USD"){
            
            if(valueMax==AppConfig.FilterProductConfig.priceRangeMax){
                self.range_slary_label.text = "\("Price".localized): \(valueMin) - \(valueMax)+ \(c)"
            }else{
                self.range_slary_label.text = "\("Price".localized): \(valueMin) - \(valueMax) \(c)"
            }
            
            
            if(valueMax==AppConfig.FilterProductConfig.priceRangeMax){
                ex_parameters["price_max"] = "0"
                ex_parameters["price_min"] = String(valueMin)
            }else{
                ex_parameters["price_max"] = String(valueMax)
                ex_parameters["price_min"] = String(valueMin)
            }
           
           
        }
       
        
    }
    
    var selected_category: Category? = nil
    
    let currency = SyncAppConfig.findById(id: "DEFAULT_CURRENCY")
    
    override func setup() {
        
        guard !initialized else {
            return
        }
        
        super.setup()
       
        self.radius_label.initDefaultFont()
        self.range_slary_label.initDefaultFont()
        self.category_label.initBolodFont()
    
        self.search_field.initDefaultFont()
        self.search_field.titleLabel.initDefaultFont()
        
        self.category_label.text = "Select Category".localized
        
        self.radius_label.text = "\("Radius".localized) \(AppConfig.distanceMaxValue) \(AppConfig.distanceUnit.localized)"
      
        if let c  = currency?.getValue(defaultValue: "USD"){
            self.range_slary_label.text = "\("Price".localized): \(AppConfig.FilterProductConfig.priceRangeMin) - \(AppConfig.FilterProductConfig.priceRangeMax)+ \(c)"
            
        }
        
        rangeSlider_Salary_View.trackHighlightTintColor = Colors.primaryColor
        rangeSlider_Salary_View.minimumValue = Double(AppConfig.FilterProductConfig.priceRangeMin)
        rangeSlider_Salary_View.maximumValue = Double(AppConfig.FilterProductConfig.priceRangeMax)
        rangeSlider_Salary_View.lowerValue = Double(AppConfig.FilterProductConfig.priceRangeMin)
        rangeSlider_Salary_View.upperValue = Double(AppConfig.FilterProductConfig.priceRangeMax)
        
        
        ex_parameters["price_max"] = String(AppConfig.FilterProductConfig.priceRangeMin)
        ex_parameters["price_min"] = String(AppConfig.FilterProductConfig.priceRangeMin)
        
        
         self.search_field.textColor = Colors.black
              self.search_field.lineColor = UIColor.gray
              self.search_field.selectedTitleColor = Colors.black
              self.search_field.selectedLineColor = Colors.primaryColor
              self.search_field.selectedLineHeight = 1.5
              self.search_field.lineHeight = 0.5
              self.search_field.titleColor = Colors.primaryColor
              self.search_field.titleLabel.textColor = Colors.black
              
        self.search_field.placeholder = "Write something ...".localized
        
        

        self.sliderView.minimumValue = Float(0)
        self.sliderView.maximumValue = Float(AppConfig.distanceMaxValue)
        self.sliderView.value = Float(AppConfig.distanceMaxValue)
        
        self.sliderView.tintColor = Colors.primaryColor

        self.radius_label.text = "\("Radius".localized) +\(999) \(AppConfig.distanceUnit.localized)"
    
        self.search_field.delegate = self
        
       // self.setupFilterViews()
        self.setupCategoryList()
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: UIResponder.keyboardWillHideNotification, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: UIResponder.keyboardWillShowNotification, object: nil)
          
    }
    
    func setupCategoryList() {
        
        let filter1 =  UINib(nibName: "FilterCheckBox", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! FilterCheckBox
          
          filter1.heightAnchor.constraint(equalToConstant: 40).isActive = true
          
        
        filter1.isMultiple = true
        filter1.current = "select_category"
        
        var list_categories_obj: [FilterObjStruct] = []
        let list = Category.getAll()
        
        
        
        let object = FilterObjStruct(id: -1,
            order: -1,
            title: "All".localized,
            group: "",
            group_title: "",
            isMultiple: false
         )
        
        list_categories_obj.append(object)
        
        
        for c in list{
            
            let object = FilterObjStruct(id: c.numCat,
                order: c.numCat,
                title: c.nameCat,
                group: "",
                group_title: "",
                isMultiple: false
             )
            
            list_categories_obj.append(object)
            
        }

        filter1.setup(items: list_categories_obj)
        filter1.isMultiple = false
        filter1.delegate = self
        
         
        category_container.addSubview(filter1)
        
        
       filter1.toggle(id: -1)
        
        filter1.translatesAutoresizingMaskIntoConstraints = false
        let constraints = [
            filter1.topAnchor.constraint(equalTo: category_container.topAnchor, constant: 0),
            filter1.leadingAnchor.constraint(equalTo: category_container.leadingAnchor, constant: 0),
            filter1.bottomAnchor.constraint(equalTo: category_container.bottomAnchor, constant: 0),
            filter1.trailingAnchor.constraint(equalTo: category_container.trailingAnchor, constant: 0),
        ]
        NSLayoutConstraint.activate(constraints)
        
    }
    
    
  
    
    func setupFilterViews() {
        
        let data_list = FilterObject.getGrouped()
       
        for (_,list) in Array(data_list).sorted(by: {$0.0 < $1.0}) {
            
            let filter1 =  UINib(nibName: "FilterCheckBox", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! FilterCheckBox
              
              filter1.heightAnchor.constraint(equalToConstant: 40).isActive = true
            
                filter1.current = list[0].group
            
            let label = createLabel(text: list[0].group_title.localized);
              stackView.addArrangedSubview(label)
             
            filter1.setup(items: list)
            filter1.isMultiple = list[0].isMultiple
            filter1.delegate = self
            
              
            stackView.addArrangedSubview(filter1)
            
            
        }
      
    }
    
    func onClicked(current: String, selected_items: [Int]) {
        
        if current == "select_category"{
            Utils.printDebug("\(selected_items)")
            
            if selected_items.count > 0{
                ex_parameters["category_id"] = String(selected_items[0])
            }
           //
        }else if current != ""{
            
            if selected_items.count > 0{
                var items: [String] =  []
                for i in selected_items{
                    items.append(String(i))
                }
                
                ex_parameters[current] = items.joined(separator: ",")
            }else{
                ex_parameters[current] = ""
            }
           
        }
        
       
        
    }
    
    func createLabel(text:String) -> UIView {
        
        let view = UIView()
        view.backgroundColor  = .clear
       
        let label = EdgeLabel()
        label.text  = text
        label.initBolodFont()
        label.textColor = .black
        
        view.addSubview(label)
        
        label.translatesAutoresizingMaskIntoConstraints = false
        let constraints = [
            label.topAnchor.constraint(equalTo: view.topAnchor, constant: 0),
            label.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            label.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0),
            label.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 20),
        ]
        
        NSLayoutConstraint.activate(constraints)
    
        label.heightAnchor.constraint(equalToConstant: 40).isActive = true
        
        
        return view
    }
      
      
      @objc func handleKeyboardNotification(notification: NSNotification) {
          
          let isKeyboardShowing = notification.name == UIResponder.keyboardWillShowNotification
          
          if isKeyboardShowing{
              // so increase contentView's height by keyboard height
              UIView.animate(withDuration: 0.3, animations: {
                  //self.constraintContentHeight.constant = -100
                  self.layoutIfNeeded()
              })
              
          }else{
              // so increase contentView's height by keyboard height
              UIView.animate(withDuration: 0.3, animations: {
                  //self.constraintContentHeight.constant = 0
                  self.layoutIfNeeded()
              })
              
          }
          
          
      }
      
      
      var nbrPress = 0
      override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
          self.endEditing(true)
      }
      
      
      
      var lastTextField: UITextField? = nil
        
        func textFieldDidBeginEditing(_ textField: UITextField) {
        
            lastTextField = textField
        }
        
      
      
      func textFieldShouldReturn(_ textField: UITextField) -> Bool {
          textField.resignFirstResponder()
          lastTextField = textField
          return true
      }
    
    
    
    func onChange(key: String, activeView: UIButton, views: [String : UIButton]) {
        
      
    }
    
    
  
    
  
    
}
