//
//  OrderFormView.swift
//  NSApplication1.8
//
//  Created by Amine  on 5/9/20.
//  Copyright © 2020 Amine. All rights reserved.
//

import UIKit

class OrderFormView : OrderSimpleView{
    
    var cf: CustomFields?
    var fields_positions: [Int] = []
  
    func setupCF() {
        
        guard let custom_field = self.cf else {
            return
        }
        
        guard stackView.subviews.count == 0 else {
            return
        }
        
        
        Utils.printDebug("\(custom_field)")
        
        let label1 = UILabel(frame: CGRect(x: 0, y: 0, width: stackView.frame.width, height: 45))
              
        label1.initBolodFont(size: 20)
        label1.text = "Detail".localized
        stackView.addArrangedSubview(label1)
        
        
        
        for field in custom_field.fields{
        
            
            fields_positions.append(stackView.subviews.count)
            
            if(field.type == "input.phone"){
                
                let textField = OPhoneField.newInstance().setup(field: field)
                stackView.addArrangedSubview(textField)
                
                textField.labelView?.keyboardType = .phonePad
                textField.viewController = viewController
                
                let cache = CustomFields.get_cache(id: custom_field.id, key: textField.getKey())
                textField.labelView!.text = cache
                
            }else if(field.type == "input.email"){
                
                let textField = OTextField.newInstance().setup(field: field)
                stackView.addArrangedSubview(textField)
                
                textField.labelView?.keyboardType = .emailAddress
                textField.viewController = viewController
                
                let cache = CustomFields.get_cache(id: custom_field.id, key: textField.getKey())
                textField.labelView!.text = cache
                
                
            }else if(field.type == "input.number"){
                
                let textField = OTextField.newInstance().setup(field: field)
                stackView.addArrangedSubview(textField)
                
                textField.labelView?.keyboardType = .numberPad
                textField.viewController = viewController
                
                let cache = CustomFields.get_cache(id: custom_field.id, key: textField.getKey())
                textField.labelView!.text = cache
                
                
            }else if(field.type == "input.text"){
                
                let textField = OTextField.newInstance().setup(field: field)
                stackView.addArrangedSubview(textField)
                
                textField.labelView?.keyboardType = .default
                textField.viewController = viewController
                
                let cache = CustomFields.get_cache(id: custom_field.id, key: textField.getKey())
                textField.labelView!.text = cache
                
            }else if(field.type == "textarea.longtext"){
                
                let longTextField = OLongTextField.newInstance().setup(field: field)
                stackView.addArrangedSubview(longTextField)
                
                longTextField.viewController = viewController
                
                let cache = CustomFields.get_cache(id: custom_field.id, key: longTextField.getKey())
                
                if(cache != ""){
                    longTextField.labelView!.text = cache
                }
              
                
            }else if(field.type == "input.location"){
                
                let locationField = OAddressLocationField.newInstance().setup(field: field)
                stackView.addArrangedSubview(locationField)
                
                locationField.viewController = viewController
                
                let cache = CustomFields.get_cache(id: custom_field.id, key: locationField.getKey())
                
                
                
                let address_arr = cache.split(separator: ";")
                
                if address_arr.count == 3{
                    let address: String = String(address_arr[0])
                    locationField.labelView.text = address
                    
                    locationField.response_address = String(address_arr[0])
                    locationField.response_lat = String(address_arr[1])
                    locationField.response_lng = String(address_arr[2])
                    locationField.button.setIcon(icon: .ionicons(.androidLocate), iconSize: 22, color: Colors.primaryColor, forState: .normal)
                    
                }
               
            }else if(field.type == "input.date"){
                
                let dateField = ODateField.newInstance().setup(field: field)
                stackView.addArrangedSubview(dateField)
                
                dateField.labelView?.keyboardType = .default
                dateField.viewController = viewController
                
                let cache = CustomFields.get_cache(id: custom_field.id, key: dateField.getKey())
                dateField.labelView!.text = cache
                
            }else if(field.type == "input.time"){
                
                let timeField = OTimeField.newInstance().setup(field: field)
                stackView.addArrangedSubview(timeField)
                
                timeField.labelView?.keyboardType = .default
                timeField.viewController = viewController
                
                let cache = CustomFields.get_cache(id: custom_field.id, key: timeField.getKey())
                timeField.labelView!.text = cache
                
            }
            
                         
        }
  
        
    }
    
    
    func getErrors() -> [String: String]{
         
         var errors: [String: String] = [:]
         
         for index in fields_positions{
            
             let view = stackView.subviews[index]
             
             if view.isKind(of: OTextField.self){
                 
                let ofield = view as! OTextField
                
                if let field = ofield.getField(), field.required == 1, ofield.getValue() == ""{
                    errors[ofield.getKey()] = "Field %@ is required".format(arguments: ofield.getKey()).localized
                    ofield.labelView!.errorMessage = errors[ofield.getKey()]
                }
                 
             }else if view.isKind(of: OLongTextField.self){
                 
                let ofield = view as! OLongTextField
                
                if let field = ofield.getField(), field.required == 1, ofield.getValue() == ""{
                    errors[ofield.getKey()] = "Field %@ is required".format(arguments: ofield.getKey()).localized
                }
                 
             }else if view.isKind(of: OPhoneField.self){
                
                let ofield = view as! OPhoneField
                
                if let field = ofield.getField(), field.required == 1, ofield.getValue() == ""{
                    errors[ofield.getKey()] = "Field %@ is required".format(arguments: ofield.getKey()).localized
                }
                
                if ofield.getValue() != "" {
                    let phone = ofield.getValue().replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
                    if !phone.isValid(regex: .phone){
                        errors[ofield.getKey()] = "Field %@ is not valid!".format(arguments: ofield.getKey()).localized
                    }
                }
                 
             }else if view.isKind(of: OAddressLocationField.self){
                 
                let ofield = view as! OAddressLocationField
                 
                if let field = ofield.getField(), field.required == 1, ofield.getValue() == ""{
                    errors[ofield.getKey()] = "Field %@ is required".format(arguments: ofield.getKey()).localized
                    ofield.labelView.errorMessage = errors[ofield.getKey()]
                }
             }
             
         }
         
        
       
         return errors
         
     }
    
    func getParameters() -> [KeyValue]{
        
        var parameters0: [String: String] = [:]
        
        for index in fields_positions{
            let view = stackView.subviews[index]
            
            if view.isKind(of: OField.self){
                let ofield = view as! OField
                parameters0[ofield.getKey()] = ofield.getValue()
            }else if view.isKind(of: OAddressLocationField.self){
                let ofield = view as! OAddressLocationField
                parameters0[ofield.getKey()] = ofield.getValue()
            }
            
        }
        
        //re order paramerter
        var parameters: [KeyValue] = []
        
        if let custom_field = self.cf {
            for field in custom_field.fields{
                parameters.append(  KeyValue(key: field.label, value: parameters0[field.label]!)  )
            }
        }
        
        Utils.printDebug("\(parameters)")
   
        return parameters
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var stackView: UIStackView!
    @IBOutlet weak var constraintScrollBottom: NSLayoutConstraint!
    
    override func setup() {
        
        stackView.translatesAutoresizingMaskIntoConstraints = false
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name:  UIResponder.keyboardWillHideNotification, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name:  UIResponder.keyboardWillShowNotification, object: nil)
    }
    
    
    var lastTextField: UITextField? = nil
    
    @objc func handleKeyboardNotification(notification: NSNotification) {
        
        
        if let userInfo = notification.userInfo {
            
            let keyboardFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
            let isKeyboardShowing = notification.name == UIResponder.keyboardWillShowNotification
            
            
             if isKeyboardShowing{
                               // so increase contentView's height by keyboard height
                    self.constraintScrollBottom.constant = keyboardFrame.height
                    UIView.animate(withDuration: 0, delay: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
                        self.layoutIfNeeded()
                    })
                               
            }else{
                               // so increase contentView's height by keyboard height
                    self.constraintScrollBottom.constant = 20
                    UIView.animate(withDuration: 0, delay: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
                        self.layoutIfNeeded()
                    })
                               
            }
            
            
        }
        
        
    }
    
    
    
    
}

struct KeyValue {
    var key: String
    var value: String
}


