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

import UIKit

class TransactionViewController: UIViewController {
    
    @IBOutlet weak var appText: UILabel!
    @IBOutlet weak var appLogo: UIImageView!
    
    @IBOutlet weak var navigationBar: UINavigationItem!
    
    let transition = TransactionMenuTransitionManager()
    var transactionActionLable : UILabel!
    var transactionView : UIView!
    var transactionHeaderView :UIView!
    var errorLable : UILabel!
    var transactionAction : TransactionActionType!
    var transaction :TransactionOption!
    // TODO: UPDATE WITH YOUR OWN PARAMETERS
    var headerDict: [String:String] = ["API-Protocol":"https",
                                       "API-Host-Name":"api.sandbox.zeamster.com",
                                       "API-Endpoint-Path":"/v2/transactions",
                                       "User-Id": "11ec11a758ee65caa5262645",
                                       "User-API-Key": "11ec43d3a43d43e483713f77",
                                       "Developer-Id": "HwJd35Z6"]
    
    @IBOutlet weak var containerView: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
        configureUIControls()
    }
    
    func configureUIControls() {
        let button = UIButton()
        button.frame = CGRect(x: 0, y: 0, width: 55, height: 55)
        button.setImage(UIImage(named: "ToggleIcon"), for: .normal)
        button.addTarget(self, action: #selector(menuBarButtonClicked), for: .touchUpInside)
        button.adjustsImageWhenHighlighted = false
        let barButton = UIBarButtonItem()
        barButton.customView = button
        navigationBar.leftBarButtonItem = barButton
        
        appLogo.frame = CGRect(x: (self.view.bounds.width*0.5)-50, y: 50, width: 100, height: 200)
        appText.frame = CGRect(x: (self.view.bounds.width*0.5)-150, y: 250, width: 300, height: 60)
    }
}
extension TransactionViewController: MenuTransitionManagerDelegate{
    func dismiss() {
        dismiss(animated: true, completion: nil)
    }
    
    //MARK :- Transaction Menu Button Clicked
    @objc func menuBarButtonClicked(_ sender: Any) {
        performMenuTransition()
    }
    public func performMenuTransition()   {
        guard let transactionMenuController = storyboard?.instantiateViewController(withIdentifier: "TransactionMenuController") as? TransactionMenuController else{return}
        transactionMenuController.selectedTransactionMenu = {transactionMenuType in
            self.transitionToNewContent(transactionMenuType)
        }
        transactionMenuController.modalPresentationStyle = .overCurrentContext
        transactionMenuController.transitioningDelegate = self
        transition.delegate = self as MenuTransitionManagerDelegate
        present(transactionMenuController, animated: true)
        
        
    }
    
    
    func transitionToNewContent(_ menuType: TransactionOption) {
        self.title = menuType.description
        loadTransactionScreen(menuType)
        
    }
}

//MARK :- Transaction Menu Transition Section

extension TransactionViewController: UIViewControllerTransitioningDelegate {
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        transition.isPresenting = true
        return transition
    }
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        transition.isPresenting = false
        return transition
    }
}

//MARK :- Transaction Action Section
extension TransactionViewController {
    
    public func loadTransactionScreen( _ transactionType :TransactionOption) {
        
        transaction = transactionType
        if transactionType == TransactionOption.Transactions {
            if transactionActionLable != nil {
                transactionActionLable.removeFromSuperview()
            }
            if transactionView != nil {
                transactionView.removeFromSuperview()
            }
            appLogo.frame = CGRect(x: (self.view.bounds.width*0.5)-50, y: 50, width: 100, height: 200)
            appText.frame = CGRect(x: (self.view.bounds.width*0.5)-150, y: 250, width: 300, height: 60)
            appLogo.isHidden = false
            appText.isHidden = false
            
        }
        else {
            appLogo.isHidden = true
            appText.isHidden = true
            if transactionActionLable != nil {
                transactionActionLable.removeFromSuperview()
            }
            transactionActionLable = UILabel(frame: CGRect(x:( (view.bounds.width*0.5 )-200), y: 20, width: 400, height: 25))
            
            transactionActionLable.textColor = .black
            transactionActionLable.font = UIFont.systemFont(ofSize: 30,weight: .bold)
            if(transactionType == TransactionOption.EMVTransaction) {
                transactionActionLable.text = "Transaction Actions"
            } else {
                transactionActionLable.text = "Select Device"
            }
            transactionActionLable.textAlignment = .center
            containerView.addSubview(transactionActionLable)
            
            if transactionView != nil {
                transactionView.removeFromSuperview()
            }
            
            transactionView = UIView()
            transactionView.backgroundColor = .white
            transactionView.frame = CGRect(x: 0, y: 80, width:
                view.bounds.width, height: containerView.bounds.height)
            containerView.addSubview((transactionView))
            
            var transactionActionTypes: [TransactionActionType]!
            var yValue = transactionView.bounds.minY + 5
            let xValue = (view.bounds.width*0.5) - 125
            if transactionType == TransactionOption.RouterTransaction {
                transactionActionTypes = [TransactionActionType.Sale,TransactionActionType.Refund, TransactionActionType.AuthOnly,TransactionActionType.AuthIncrement,TransactionActionType.AuthComplete]
            }
            if transactionType == TransactionOption.CreditCardTransaction {
                transactionActionTypes = [TransactionActionType.Sale,TransactionActionType.Refund,TransactionActionType.AVSOnly,TransactionActionType.AuthOnly,TransactionActionType.AuthIncrement,TransactionActionType.AuthComplete,TransactionActionType.Force]
            }
            if transactionType == TransactionOption.ACHTransaction {
                transactionActionTypes = [TransactionActionType.Debit,TransactionActionType.Credit, TransactionActionType.Refund,TransactionActionType.AVSOnly]
            }
            if transactionType == TransactionOption.GenericTransaction {
                transactionActionTypes = [TransactionActionType.Void,TransactionActionType.Edit, TransactionActionType.ViewRecord,TransactionActionType.ViewRecordList,TransactionActionType.TipAdjust,TransactionActionType.BinInfo]
            }
            if transactionType == TransactionOption.RouterAccountVaults {
                transactionActionTypes = [TransactionActionType.Store]
            }
            if transactionType == TransactionOption.EMVTransaction {
                let deviceList = [EMVDevices.VP3300, EMVDevices.VP8800]
                for device in deviceList {
                    let deviceButton = UIButton()
                    deviceButton.setTitle(device.rawValue, for: .normal)
                    deviceButton.titleLabel?.font = UIFont.systemFont(ofSize: 25,weight: .bold)
                    
                    deviceButton.tintColor = .white
                    deviceButton.frame = CGRect(x: xValue, y: yValue, width: 250, height: 60)
                    deviceButton.addTarget(self, action: #selector(transactionActionButtonClicked), for: .touchUpInside)
                    deviceButton.layer.insertSublayer(setGradientBackgroundWithShadow( buttonBounds:deviceButton.bounds), at: 0)
                    transactionView.addSubview(deviceButton)
                    yValue = yValue + 80
                }
            } else {
                for transactionActionType in transactionActionTypes {
                    let transactionActionButton = UIButton()
                    transactionActionButton.setTitle(transactionActionType.rawValue, for: .normal)
                    transactionActionButton.titleLabel?.font = UIFont.systemFont(ofSize: 25,weight: .bold)
                    
                    transactionActionButton.tintColor = .white
                    transactionActionButton.frame = CGRect(x: xValue, y: yValue, width: 250, height: 60)
                    transactionActionButton.addTarget(self, action: #selector(transactionActionButtonClicked), for: .touchUpInside)
                    transactionActionButton.layer.insertSublayer(setGradientBackgroundWithShadow( buttonBounds:transactionActionButton.bounds), at: 0)
                    transactionView.addSubview(transactionActionButton)
                    yValue = yValue + 80
                }
            }
        }
    }
    @objc func transactionActionButtonClicked(_ sender: UIButton){
        let action = sender.titleLabel?.text ?? ""
        let transactionAction = TransactionActionType.init(rawValue: action)
        loadTransactionHeaderScreen(tranctionActionType: transactionAction ?? TransactionActionType.Sale, action: action)
    }
}


//MRAK :- Transaction Header Section
extension TransactionViewController {
    func  loadTransactionHeaderScreen( tranctionActionType: TransactionActionType?, action: String){
        
        transactionAction = tranctionActionType
        
        for currentView in transactionView.subviews {
            currentView.removeFromSuperview()
        }
        transactionActionLable.textColor = .black
        transactionActionLable.text = "Header Information"
        
        transactionHeaderView = UIView()
        transactionHeaderView.frame = CGRect(x: 5, y: (transactionActionLable.bounds.maxY)-30, width:
            containerView.bounds.width-5, height:380)
    transactionHeaderView.layer.insertSublayer(setGradientBackgroundWithShadow(buttonBounds: transactionHeaderView.bounds), at: 0)
        
        transactionView.addSubview((transactionHeaderView))
        let transactionHeaderInputs : [String] = ["API Protocol","API Host Name","API Endpoint Path","User Id","User API Key","Developer Id", "Transaction Id"]
        var heightValue = transactionHeaderView.bounds.minY + 20
        var tagValue = 1
        for transactionHeaderInput in transactionHeaderInputs {
            let inputLabel = UILabel(frame: CGRect(x:15, y:heightValue, width: (transactionHeaderView.bounds.width*0.5), height: 40))
            inputLabel.textColor = .white
            inputLabel.font = UIFont.systemFont(ofSize: 18,weight: .bold)
            inputLabel.text = transactionHeaderInput + ": "
            inputLabel.textAlignment = .left
            transactionHeaderView.addSubview(inputLabel)
            let inputField =  UITextField(frame: CGRect(x: (transactionHeaderView.bounds.width*0.5) - 10, y: heightValue, width: (transactionHeaderView.bounds.width*0.5), height: 40))
            inputField.delegate = self
            inputField.font = UIFont.systemFont(ofSize: 18)
            inputField.borderStyle = UITextField.BorderStyle.roundedRect
            inputField.backgroundColor = .white
            inputField.autocorrectionType = UITextAutocorrectionType.no
            inputField.keyboardType = UIKeyboardType.default
            inputField.returnKeyType = UIReturnKeyType.done
            inputField.clearButtonMode = UITextField.ViewMode.whileEditing
            inputField.autocapitalizationType = .none
            inputField.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center
            inputField.tag = tagValue
            inputField.accessibilityIdentifier = transactionHeaderInput.replacingOccurrences(of: " ", with: "-")
            inputField.text = headerDict[transactionHeaderInput.replacingOccurrences(of: " ", with: "-")]
            if tagValue == 1 {
                inputField.becomeFirstResponder()
            }
            transactionHeaderView.addSubview(inputField)
            heightValue = heightValue + 50
            tagValue += 1
        }
        
        let nextButton = UIButton()
        nextButton.setTitle("Next", for: .normal)
        nextButton.titleLabel?.font = UIFont.systemFont(ofSize: 25,weight: .bold)
        nextButton.tintColor = .white
        nextButton.frame = CGRect(x: ( (containerView.bounds.width*0.5 )-100), y: transactionHeaderView.bounds.maxY+30, width: 200, height: 50)
        
        let gradientLayer = CAGradientLayer()
        gradientLayer.cornerRadius = 5
        gradientLayer.frame = nextButton.bounds
        gradientLayer.colors = [#colorLiteral(red: 0.02803416736, green: 0.6146276593, blue: 0.9531614184, alpha: 1).cgColor,#colorLiteral(red: 0.085551925, green: 0.5000404119, blue: 0.7664285302, alpha: 1).cgColor]
        gradientLayer.locations = [0.0, 1.0]
        gradientLayer.startPoint = CGPoint(x:1.0,y:1.0)
        gradientLayer.endPoint = CGPoint(x: 0.0, y:0.0)
        gradientLayer.shadowColor = #colorLiteral(red: 0.085551925, green: 0.5000404119, blue: 0.7664285302, alpha: 1)
        gradientLayer.shadowRadius = 10
        gradientLayer.shadowOpacity = 0.5
        gradientLayer.shadowOffset = CGSize(width: 0, height: 0)
        nextButton.layer.insertSublayer(gradientLayer, at: 0)
        nextButton.addTarget(self, action: #selector(nextButtonClicked), for: .touchUpInside)
        if(action.starts(with: "Vivo")) {
            nextButton.tag = 1
        }
        transactionView.addSubview(nextButton)
        
        errorLable = UILabel(frame: CGRect(x:15, y:(transactionHeaderView.bounds.maxY+100), width: (transactionView.bounds.width), height: 30))
        errorLable.textColor = .red
        errorLable.font = UIFont.systemFont(ofSize: 20)
        errorLable.text = "Error!"
        errorLable.textAlignment = .left
        transactionView.addSubview(errorLable)
        errorLable.isHidden=true
    }
    @objc func nextButtonClicked(sender: UIButton) {
        headerDict = [:]
        guard let viewController =
            storyboard?.instantiateViewController(withIdentifier: "TransactionParameterController") else {return}
        let transactionParameterController = viewController as!TransactionParameterController
        for headerInnerView in transactionHeaderView.subviews  {
            if headerInnerView is UITextField {
                let inputField = headerInnerView as! UITextField
                if inputField.text != nil {
                    if inputField.accessibilityIdentifier == "Transaction-Id" && inputField.text == ""{
                        headerDict[inputField.accessibilityIdentifier ?? "incorrectData"] = inputField.text
                    }
                    else if inputField.text != ""  {  headerDict[inputField.accessibilityIdentifier ?? "incorrectData"] = inputField.text
                    }
                }
            }
        }
        if headerDict.count != 7 {
            errorLable.text = "Incomplete transaction header detail."
            errorLable.isHidden = false
        }
        else {
            if(sender.tag == 1) {
                transactionParameterController.isEMV = true
            }
            transactionParameterController.transactionHeaderDict = headerDict
            transactionParameterController.transactionActionType = transactionAction
            loadTransactionScreen(transaction)
            self.navigationController?.pushViewController(transactionParameterController, animated: true)
            
        }
    }
}

extension TransactionViewController: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        textField.becomeFirstResponder()
    }
    func textFieldDidEndEditing(_ textField: UITextField) {
        textField.resignFirstResponder()
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.view.endEditing(true)
        return false
    }
}
