//
//  TransactionParameterController.swift
//  ZeamsterPayementSDKApp
//
//  Created by Apple on 12/09/19.
//  Copyright © 2019 None. All rights reserved.
//


import UIKit
class TransactionParameterController: UIViewController {
    
    var transactionHeaderDict : [String : String]!
    var transactionActionType :TransactionActionType!
    var transactionInputDict : [String:String] = [:]
    var inputRowTopHeight :CGFloat = 0
    var inputFieldTag = 1
    var transactionInputList = transactionInputs.sorted()
    var isEMV = false
    
    @IBOutlet weak var transactionInputSelectionButton: UIButton!
    @IBOutlet weak var transactionInputTableView: UITableView!
    
    @IBOutlet weak var transactionInputContainerView: UIView!
    @IBOutlet weak var submitButton: UIButton!
    
    var selectionTableView = UITableView()
    let inputSelectionButton = UIButton()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configureUIControls()
        
        // Add our own items
        // TODO: UPDATE WITH YOUR OWN LOCATION ID AND OTHER PARAMS.
        addTransactionInputSection(transactionInputText:"Payment Method",transactionInputData: "cc", addButtonCall: false)
        addTransactionInputSection(transactionInputText:"Type Id",transactionInputData: "sale", addButtonCall: false)
        addTransactionInputSection(transactionInputText:"Location Id",transactionInputData: "11ec11a757d6b13897cd1f3c", addButtonCall: false)
        addTransactionInputSection(transactionInputText:"Transaction Amount",transactionInputData: "155.00", addButtonCall: false)

    }
    
    func configureUIControls()  {
        
        transactionInputTableView.delegate=self
        transactionInputTableView.dataSource=self
        transactionInputTableView.isHidden=true
        transactionInputSelectionButton.layer.cornerRadius = 5
        transactionInputTableView.layer.cornerRadius = 5
        transactionInputTableView.layer.borderWidth = 2
        transactionInputTableView.layer.borderColor = #colorLiteral(red: 0, green: 0.3285208941, blue: 0.5748849511, alpha: 1)
    transactionInputSelectionButton.layer.insertSublayer(setGradientBackgroundWithShadow(buttonBounds: transactionInputSelectionButton.bounds), at: 0)
        
        submitButton.layer.cornerRadius = 5
    submitButton.layer.insertSublayer(setGradientBackgroundWithShadow(buttonBounds: submitButton.bounds), at: 0)
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissView))
        transactionInputContainerView.addGestureRecognizer(tapGesture)
        transactionInputList.sort()
        
    }
    @objc func dismissView() {
        animateTransactionInputTable(toggle: false)
    }
    //MARK :- Transaction Parameter Selection Button Click
    @IBAction func transactionSelectionButtonClicked(_ sender: Any) {
        
        if transactionInputTableView.isHidden {
            
            animateTransactionInputTable(toggle: true)
        }
        else {
            animateTransactionInputTable(toggle: false)
        }
    }
    
    func animateTransactionInputTable(toggle: Bool) {
        if toggle {
            UIView.animate(withDuration: 0.3) {
                self.transactionInputTableView.isHidden = false
            }
        }
        else {
            UIView.animate(withDuration: 0.3) {
                self.transactionInputTableView.isHidden = true
            }
        }
        
    }
    
    //MARK :- Transaction Parameter Add Button Click
    
    @IBAction func addTransactionInputButtonClicked(_ sender: Any){
        let transactionInputValue = transactionInputSelectionButton.titleLabel?.text ?? ""
        transactionInputSelectionButton.setTitle("Select Transaction Parameter", for: .normal)
        animateTransactionInputTable(toggle: false)
        addTransactionInputSection(transactionInputText:transactionInputValue,transactionInputData: "", addButtonCall: true)
        
        
    }
    
    
    //MARK :- Transaction Submit Button Click
    
    @IBAction func transactionSubmitButtonClicked(_ sender: Any) {
        transactionInputDict = [:]
        transactionInputContainerView?.subviews.forEach{
            if let subview = $0 as? UITextField{
                if subview.accessibilityIdentifier != "" {
                    transactionInputDict[String(subview.accessibilityIdentifier?.lowercased() ?? "")] = (subview.text ?? "")
                }
            }
        }
        if !transactionInputTableView.isHidden {
            animateTransactionInputTable(toggle: false)
        }
        
        if(self.isEMV) {
            // Safe Push VC
            if let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "EMVView") as? EMVTransactionViewController {
                
                if let navigator = navigationController {
                    viewController.transactionHeaderDict = transactionHeaderDict
                    viewController.transactionParamDict = transactionInputDict
                    viewController.transactionAction = transactionActionType
                    navigator.pushViewController(viewController, animated: true)
                }
            }
        } else {
            guard let viewController =
                storyboard?.instantiateViewController(withIdentifier: "TransactionResultController") else {return}
            let transactionResultontroller = viewController as! TransactionResultController
            
            transactionResultontroller.transactionHeaderDict = transactionHeaderDict
            transactionResultontroller.transactionParamDict = transactionInputDict
            transactionResultontroller.transactionAction = transactionActionType
            self.navigationController?.pushViewController(transactionResultontroller, animated: true)
        }
    }
    
    
    
    //MARK :- Add the transaction parameter section
    
    func  addTransactionInputSection(transactionInputText :String?, transactionInputData :String?,addButtonCall: Bool) {
        var transactionInput = ""
        var transactionInputValue = ""
        if inputRowTopHeight == 0{
            inputRowTopHeight = transactionInputContainerView.bounds.minY + 5
        }
        
        if transactionInputText != "" {
            transactionInput = transactionInputText ?? ""
        }
        if transactionInputData != "" {
            transactionInputValue = transactionInputData ?? ""
        }
        if transactionInput != "Select Transaction Parameter" {
            if addButtonCall && transactionInputDict[(transactionInput.replacingOccurrences(of: "_", with: " "))] != nil {
                //Do nothing
            }
            else {
                transactionInputList.removeAll { $0 == transactionInput}
                transactionInputList.sort()
                transactionInputTableView.reloadData()
                
                
                transactionInputDict[(transactionInput.replacingOccurrences(of: "_", with: " "))] = transactionInputValue
                let borderLine = UIView(frame: CGRect(x: 0, y: inputRowTopHeight, width: transactionInputContainerView.bounds.width, height: 2))
                borderLine.backgroundColor = .groupTableViewBackground
                borderLine.accessibilityIdentifier = transactionInput.trimmingCharacters(in: .whitespaces)
                let inputLabel = UILabel(frame: CGRect(x:15, y: inputRowTopHeight+5, width: (transactionInputContainerView.bounds.width*0.5), height: 30))
                inputLabel.textColor = .black
                inputLabel.font = UIFont.systemFont(ofSize: 15)
                inputLabel.text = (transactionInput ) + ":"
                inputLabel.textAlignment = .left
                inputLabel.accessibilityIdentifier = transactionInput.replacingOccurrences(of: " ", with: "_")
                let inputField =  UITextField(frame: CGRect(x: transactionInputContainerView.bounds.width*0.5, y: inputRowTopHeight+5, width: (transactionInputContainerView.bounds.width*0.5)-50, height: 30))
                inputField.delegate = self
                inputField.font = UIFont.systemFont(ofSize: 15)
                inputField.borderStyle = UITextField.BorderStyle.roundedRect
                inputField.backgroundColor = .white
                inputField.autocorrectionType = UITextAutocorrectionType.yes
                inputField.keyboardType = UIKeyboardType.default
                inputField.returnKeyType = UIReturnKeyType.done
                inputField.clearButtonMode = UITextField.ViewMode.whileEditing
                inputField.autocapitalizationType = .none
                inputField.accessibilityIdentifier = transactionInput.replacingOccurrences(of: " ", with: "_")
                inputField.tag = inputFieldTag
                if addButtonCall{
                    inputField.becomeFirstResponder()
                }
                inputField.text = transactionInputValue
                inputField.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center
                
                
                let deleteButton = UIButton()
                deleteButton.setImage(UIImage(named: "DeleteIcon"), for: .normal)
                deleteButton.frame = CGRect(x: transactionInputContainerView.bounds.width - 40, y: inputRowTopHeight+5, width: 30, height: 30)
                deleteButton.addTarget(self, action: #selector(deleteButtonClicked), for: .touchUpInside)
                deleteButton.accessibilityIdentifier = transactionInput.replacingOccurrences(of: " ", with: "_")
                
                transactionInputContainerView.addSubview(borderLine)
                transactionInputContainerView.addSubview(inputLabel)
                transactionInputContainerView.addSubview(inputField)
                transactionInputContainerView.addSubview(deleteButton)
                
                inputRowTopHeight += 40
                inputFieldTag += 1
            }
        }
    }
    
    
    //MARK :- Delete selected transaction parameter
    @objc func deleteButtonClicked(_ sender: UIButton)
    {
        transactionInputDict = [:]
        let identifier = sender.accessibilityIdentifier
        sender.superview?.subviews.forEach{
            if let subview = $0 as? UITextField{
                if subview.accessibilityIdentifier != identifier {
                    transactionInputDict[(String(subview.accessibilityIdentifier ?? "")).replacingOccurrences(of: "_", with: " ")] = (subview.text ?? "")
                    
                }
                else {
                    transactionInputList.append((String(subview.accessibilityIdentifier ?? "")).replacingOccurrences(of: "_", with: " "))
                }
            }
            $0.removeFromSuperview()
        }
        inputRowTopHeight = 0
        inputFieldTag = 1
        if transactionInputDict.count != 0{
            for (key,value) in transactionInputDict {
                addTransactionInputSection(transactionInputText: key, transactionInputData: value, addButtonCall: false)
            }
        }
        else {
            transactionInputList.sort()
            transactionInputTableView.reloadData()
        }
    }
    
    //MARK :- Transaction Back Button Click
    
    @objc func transactionBackButtonClicked(_ sender: Any) {
        
        transactionInputList = transactionInputs
        transactionInputDict = [:]
        self.presentingViewController?.dismiss(animated: true)
    }
}

//MARK: Transaction Input Parameter Table
extension TransactionParameterController :UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return transactionInputList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell=tableView.dequeueReusableCell(withIdentifier: "InputCell", for: indexPath)
        cell.textLabel?.text = transactionInputList[indexPath.row]
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let currentCell = tableView.cellForRow(at: indexPath)
        transactionInputSelectionButton.setTitle(currentCell?.textLabel?.text, for: .normal)
        animateTransactionInputTable(toggle: false)
    }
    func indexPathForPreferredFocusedView(in tableView: UITableView) -> IndexPath? {
        return IndexPath(index: 0)
    }
}
extension TransactionParameterController: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        textField.becomeFirstResponder()
    }
    func textFieldDidEndEditing(_ textField: UITextField) {
        textField.resignFirstResponder()
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.view.endEditing(true)
        return false
    }
}
