//
//  SatisPayViewController.swift
//  iPOS
//
//  Created by Rat Raul on 02/03/2020.
//  Copyright © 2020 BBC. All rights reserved.
//

import Foundation
import UIKit

protocol SatispayDelegate{
    func paymentAccepted(payment: Payment)
}

class SatispayViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, PendingPaymentCellDelegate {
    
    @IBOutlet weak var tableView: UITableView!
    
    var delegate: SatispayDelegate?
    
    var payment: Payment!
    var pendingPayments: [PendingPayment] = [PendingPayment]()
    
    var timer: Timer?
    var isLoading: Bool = false
    var showActivityDialog: Bool = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.initData()
        self.addDelegates()
        self.loadPendingPayments()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        timer?.invalidate()
    }
    
    func initData(){
        self.title = Util.getString("Satispay")
        self.timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(loadPendingPayments), userInfo: false, repeats: true)
    }
    
    func addDelegates(){
        self.tableView.delegate = self
        self.tableView.dataSource = self
    }
    
    @objc func loadPendingPayments(){
        if self.isLoading{
            return
        }
        
        self.isLoading = true
        State.getSatispayPendingPayments(showActivityDialog: self.showActivityDialog) { response in
            self.pendingPayments.removeAll()
            if (SatispayViewController.checkSatispayResponse(viewController: self, response: response)){
                self.pendingPayments = response!.PendingPayments
                for payment in self.pendingPayments{
                    payment.AmountToPay = payment.AmountToPay! / 100
                }
            }
            
            self.tableView.reloadData()
            self.showActivityDialog = false
            self.isLoading = false
        }
    }
    
    public static func checkSatispayResponse(viewController: UIViewController, response: DefaultResponse?) -> Bool{
        if let response = response{
            if let resultCode = response.resultCode{
                if resultCode == 0{
                    return true
                }
                else if resultCode == 6{
                    Util.GeneralAlert(viewController: viewController, message: Util.getString("SatispayNotConfiguratedError"))
                    return false
                }
                else if resultCode == 7{
                    Util.GeneralAlert(viewController: viewController, message: Util.getString("SatispayInternalError"))
                    return false
                }
                else if resultCode == 8{
                    Util.GeneralAlert(viewController: viewController, message: Util.getString("SatispayAuthenticationError"))
                    return false
                }
                else if resultCode == 9{
                    Util.GeneralAlert(viewController: viewController, message: Util.getString("SatispayConnectionError"))
                    return false
                }
                else if resultCode == 10{
                    Util.GeneralAlert(viewController: viewController, message: Util.getString("SatispayInternalError"))
                    return false
                }
                else if resultCode == 11{
                    Util.GeneralAlert(viewController: viewController, message: Util.getString("SatispayUnexpextedError"))
                    return false
                }
            }
        }
        
        Util.GeneralAlert(viewController: viewController, message: Util.getString("SatispayUnexpextedError"))
        return false
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 49
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return Util.getString("SatispaySelectPendingPayment")
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?{
        let customLabel = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: tableView.bounds.height))
        
        customLabel.text = Util.getString(self.tableView(tableView, titleForHeaderInSection: section)!)
        customLabel.backgroundColor = UIColor.groupTableViewBackground
        customLabel.textColor = UIColor.black
        customLabel.textAlignment = .center
        return customLabel
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.pendingPayments.count
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return false
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "PendingPaymentCell")! as! PendingPaymentCell
        cell.pendingPayment = self.pendingPayments[indexPath.row]
        
        cell.lfCustomerName.text = cell.pendingPayment.CustomerName ?? ""
        cell.lfPrice.text = Util.DoubleToStringWithTwoDecimals(cell.pendingPayment.AmountToPay ?? 0)
        cell.lfCurrency.text = cell.pendingPayment.Currency ?? ""
        
        if self.payment.amount == cell.pendingPayment.AmountToPay{
            cell.btAccept.isEnabled = true
        }
        else{
            cell.btAccept.isEnabled = false
        }
        
        cell.btCancel.isEnabled = true
        cell.delegate = self

        return cell
    }
    
    func CancelButtonClicked(pendingPayment: PendingPayment) {
        self.isLoading = true
        cancelPayment(pendingPayment: pendingPayment)
    }
    
    func AcceptButtonClicked(pendingPayment: PendingPayment) {
        self.isLoading = true
        acceptPayment(pendingPayment: pendingPayment)
    }
    
    func acceptPayment(pendingPayment: PendingPayment){
        Util.AlertYesNo(viewController: self, title: "IposVision", message: Util.getString("SatispayAcceptPaymentMessage"), actionYes: {
            State.acceptSatispayPayment(id: pendingPayment.Id) { response in
                if SatispayViewController.checkSatispayResponse(viewController: self, response: response){
                    self.payment.STAN = pendingPayment.Id
                    self.delegate?.paymentAccepted(payment: self.payment)
                }
                self.isLoading = false
            }
        }, actionNo: { self.isLoading = false })
    }
    
    func cancelPayment(pendingPayment: PendingPayment){
        Util.AlertYesNo(viewController: self, title: "IposVision", message: Util.getString("SatispayCancelPaymentMessage"), actionYes: {
            State.cancelSatispayPayment(id: pendingPayment.Id) { response in
                if SatispayViewController.checkSatispayResponse(viewController: self, response: response){
                    self.showActivityDialog = true
                    self.loadPendingPayments()
                }
                self.isLoading = false
            }
        }, actionNo: { self.isLoading = false })
    }
}
