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


import UIKit
import PaymentSDK
class TransactionResultController: UIViewController {
    
    @IBOutlet var mainView: UIView!
    var transactionHeaderDict : [String : String]!
    var transactionParamDict : [String : String]!
    var transactionAction :TransactionActionType!
    let transationActionWithTransactionId  = [TransactionActionType.ViewRecord,TransactionActionType.BinInfo,TransactionActionType.Edit,TransactionActionType.TipAdjust,TransactionActionType.Void,TransactionActionType.AuthIncrement,TransactionActionType.AuthComplete,TransactionActionType.Force]
    
    var dimmingView = UIView()
    var activityIndicator = UIActivityIndicatorView()
    @IBOutlet weak var resultTextView: UITextView!
    
    @IBOutlet weak var navigationBar: UINavigationItem!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configureDimmingView()
        performTransaction()
    }
    
    
    
    func performTransaction()  {
        guard let apiProtocol = transactionHeaderDict["API-Protocol"] else { return }
        guard let  apiHostName = transactionHeaderDict["API-Host-Name"] else { return }
        guard let apiEndpointPath = transactionHeaderDict["API-Endpoint-Path"] else {return}
        guard let transactionId = transactionHeaderDict["Transaction-Id"] else { return }
        var headerDictionary :[String:String]! = [:]
        
        for key in transactionHeaderDict.keys    {
            if key == "User-API-Key" || key == "User-Id" || key == "Developer-Id" || key == "Auth-Type" || key == "User-Hash-Key" {
                headerDictionary[key.lowercased()] = transactionHeaderDict[key]
            }
        }
        //MARK :- Create  RestServiceClient class object using api call details
        let restClientService = RestServiceClient(apiProtocol:apiProtocol, apiHostName:apiHostName, apiEndpointPath:apiEndpointPath)
        
        //MARK :- Set the HTTP request header detail for RestServiceClient class object
        if restClientService.setHTTPRequestHeaders(headerParams: headerDictionary! as NSDictionary)
        {
            let parameterDictionary = (transactionParamDict as NSDictionary).mutableCopy() as! NSMutableDictionary
            //MARK :- Create  TransactionService class object using RestServiceClient class object
            let transactionService = TransactionService(restClient: restClientService)
            let transactionActionType = TransactionAction(rawValue: transactionAction!.value) ?? TransactionAction.Sale
            
            if transationActionWithTransactionId.contains(transactionAction){
                
                //MARK :- Process the transaction using TransactionService class object, transaction action and transaction parameter
                
                transactionService.processTransaction(transactionAction: transactionActionType, paramMap: parameterDictionary,transactionId: transactionId)  { (responseJSON) in
                    DispatchQueue.global().async(execute: {
                        DispatchQueue.main.sync {
                            self.showTransactionResult(responseContent: responseJSON)
                        }
                    })
                }
                
            }
            else { transactionService.processTransaction(transactionAction: transactionActionType, paramMap: parameterDictionary)  { (responseJSON) in
                DispatchQueue.global().async(execute: {
                    DispatchQueue.main.sync {
                        self.showTransactionResult(responseContent: responseJSON)
                    }
                })
                }
            }
        }
    }
    
    func configureDimmingView() {
        dimmingView.backgroundColor = .black
        dimmingView.alpha = 0.2
        dimmingView.frame = self.view.bounds
        self.view.addSubview(dimmingView)
        
        activityIndicator.center = dimmingView.center
        activityIndicator.hidesWhenStopped = true
        activityIndicator.style =  UIActivityIndicatorView.Style.whiteLarge
        dimmingView.addSubview(activityIndicator)
        activityIndicator.startAnimating()
        UIApplication.shared.beginIgnoringInteractionEvents()
        
        
    }
    func showTransactionResult(responseContent: String) {
        UIApplication.shared.endIgnoringInteractionEvents()
        self.resultTextView.text = responseContent
        self.activityIndicator.stopAnimating()
        self.dimmingView.removeFromSuperview()
        let data = responseContent.data(using: .utf8)!
        let dictionary = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
        guard let transactionResultDictionary = dictionary as? [String: Any] else{
            return
        }
        let alert :UIAlertController!
        if transactionResultDictionary["title"] != nil    {
            alert=UIAlertController(title: "Failure", message:"Error occurred while processing transaction.", preferredStyle:.alert)
        }
        else {
            alert=UIAlertController(title: "Success", message:"Transaction has been perfomed successfully!", preferredStyle:.alert)
            
        }
        let action=UIAlertAction(title: "OK", style: .default) { (action) in
        }
        alert.addAction(action)
        present(alert, animated: true, completion: nil)
    }
    func loadTransactionError(errorContent: String)  {
        self.resultTextView.text=errorContent
        let alert=UIAlertController(title: "Failure", message:"Transaction is throwing!", preferredStyle:.alert)
        let action=UIAlertAction(title: "OK", style: .default) { (action) in
        }
        alert.addAction(action)
        present(alert, animated: true, completion: nil)
    }
}
