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

import Foundation
import UIKit
import SkyFloatingLabelTextField

class MySearchView: UIView {
    
    var initialized = false
    
    func setup()  {
       
        initialized = true
        
    }
}
class StoreSearch: MySearchView,CategoryLoaderDelegate, UITextFieldDelegate, FilterCheckBoxDelegate {
  
  
    var ex_parameters: [String: String] = [
        "__req_category": "0",
        "__req_redius": String(AppConfig.distanceMaxValue),
        "__req_list_order": String(ListStoresView.Request.nearby),
        "__req_search": "",
        "__req_opening_time": "0",
    ]
    
    @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 hasProductlyLabel: UILabel!
    @IBOutlet weak var hasProductlySwitch: UISwitch!
  
    @IBOutlet weak var categories_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)"
        }
        
    }
    
    var selected_category: Category? = nil
    
    
    override func setup() {
        guard !initialized else {
           return
        }
        
        super.setup()
     
        self.hasProductlySwitch.onTintColor = Colors.primaryColor
        
        self.hasProductlyLabel.initDefaultFont()
        self.radius_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)"
        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)"
    
        search_field.delegate = self
        
    
              NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: UIResponder.keyboardWillHideNotification, object: nil)
              
              NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: UIResponder.keyboardWillShowNotification, object: nil)
              
        
            setupCategoryList()
        
        }
          
          
          @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 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"
        filter1.delegate = self
        
        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
         
        categories_container.addSubview(filter1)
        
        
       filter1.toggle(id: -1)
        
        filter1.translatesAutoresizingMaskIntoConstraints = false
        let constraints = [
            filter1.topAnchor.constraint(equalTo: categories_container.topAnchor, constant: 0),
            filter1.leadingAnchor.constraint(equalTo: categories_container.leadingAnchor, constant: 0),
            filter1.bottomAnchor.constraint(equalTo: categories_container.bottomAnchor, constant: 0),
            filter1.trailingAnchor.constraint(equalTo: categories_container.trailingAnchor, constant: 0),
        ]
        NSLayoutConstraint.activate(constraints)
        
    }
    
    
    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])
            }
        }
        
    }
    
    
    //API
    
    var loader: CategoryLoader = CategoryLoader()
    
    func updateCategories () {
        
        
        self.loader.delegate = self
        
        //Get current Location
        
        var parameters = [
            "limit"          : "100"
        ]
        
        parameters["page"] = String("1")
        
        Utils.printDebug("\(parameters)")
        
        self.loader.load(url: Constances.Api.API_USER_GET_CATEGORY,parameters: parameters)
        
    }
    
    
    
    func success(parser: CategoryParser,response: String) {
        
    
        
        if parser.success == 1 {
            
            let categories = parser.parse()
            
            Utils.printDebug("===> \(categories)")
            
            if categories.count > 0 {
                
                Utils.printDebug("Loaded \(categories.count)")
                
                //if let user = myUserSession {
                // users.validateAll(sessId: user.id)
                //}
                
                
                //Category.removeAllFromRealm()
            
             
                categories.saveAll()
                
        
            }else{
              
                
            }
            
        }else {
            
           
            
        }
        
    }
    
    
    
    
    func emptyAndReload()  {
       
    }
    
    func error(error: Error?,response: String) {
        
      
        
    }
    
    
}
