//
//  ValidateGiftCardViewController.swift
//  iPOS
//
//  Created by Zoran Albu on 6/28/18.
//  Copyright © 2018 BBC. All rights reserved.
//


import Foundation
import UIKit
import AVKit

protocol ValidateGiftCardViewControllerDelegate {
    func validatedVoucher(paymentType: PaymentType, amount: Double, voucherInfo: VoucherInfo)
}

class ValidateGiftCardViewController: UIViewController, UITextFieldDelegate, ScannerViewControllerDelegate{
    
    @IBOutlet weak var tfBarcode: UITextField!
    @IBOutlet weak var btCheckBarcode: UIButton!
    @IBOutlet weak var btScanBarcode: UIButton!
    @IBOutlet weak var btPrintGiftCard: UIButton!
    @IBOutlet weak var btUseGiftCard: UIButton!
    @IBOutlet weak var tvGiftCardReceipt: UITextView!
    
    var payments: [Payment] = [Payment]()
    var paymentType: PaymentType = PaymentType()
    var amount: Double = Double()
    var delegate: ValidateGiftCardViewControllerDelegate!
    var voucherInfo: VoucherInfo = VoucherInfo()
    var remainingValueToPay: Double = Double()
    
    var ticketType: TicketType = TicketType.Receipt
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.addTapGesture()
        self.setCaptions()
        self.tfBarcode.delegate = self
        self.tvGiftCardReceipt.isEditable = false
        self.tvGiftCardReceipt.isSelectable = false
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.customLayout()
        self.setButtonUseStatus(isEnabled: false)
        self.setButtonPrintStatus(isEnabled: false)
    }
    
    func setCaptions(){
        self.btUseGiftCard.setTitle(Util.getString("Use"), for: .normal)
        self.btPrintGiftCard.setTitle(Util.getString("Print"), for: .normal)
        self.tfBarcode.placeholder = Util.getString("InsertVoucherBarcode")
    }
    
    func addTapGesture(){
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }
    
    @objc func dismissKeyboard() {
        view.endEditing(true)
    }
    
    func customLayout(){
        self.title = self.paymentType.Name
        self.tfBarcode.font = UIFont.boldSystemFont(ofSize: 21)
        self.tfBarcode.textAlignment = .left
        
        self.tvGiftCardReceipt.layer.borderColor = UIColor.groupTableViewBackground.cgColor
        self.tvGiftCardReceipt.backgroundColor = UIColor.groupTableViewBackground
        self.tvGiftCardReceipt.textColor = UIColor.black
        self.tvGiftCardReceipt.layer.borderWidth = 1

        self.btPrintGiftCard.layer.cornerRadius = 5
        self.btPrintGiftCard.layer.borderWidth = 1
        self.btPrintGiftCard.layer.borderColor = UIColor(red: 0.12, green: 0.56, blue: 1.00, alpha: 1.0).cgColor
        
        
        self.btScanBarcode.layer.cornerRadius = 5
        self.btScanBarcode.layer.borderWidth = 1
        self.btScanBarcode.layer.borderColor = UIColor(red: 0.12, green: 0.56, blue: 1.00, alpha: 1.0).cgColor
        
        self.btCheckBarcode.layer.cornerRadius = 5
        self.btCheckBarcode.layer.borderWidth = 1
        self.btCheckBarcode.layer.borderColor = UIColor(red: 0.12, green: 0.56, blue: 1.00, alpha: 1.0).cgColor
        
        self.btUseGiftCard.layer.cornerRadius = 5
        self.btUseGiftCard.layer.borderWidth = 1
        self.btUseGiftCard.layer.borderColor = UIColor(red: 0.12, green: 1.00, blue: 0.56, alpha: 1.0).cgColor
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        view.endEditing(true)
        self.checkBarcode()
        return true
    }
    
    func checkBarcode(){
        if let textBarcode = tfBarcode.text{
            let barcode = textBarcode.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
            if barcode.isEmpty{
                return
            }
            else{
                let voucher: ValidateVoucherRequest = ValidateVoucherRequest()
                voucher.voucherCode = barcode
                State.validateVoucher(voucherRequest: voucher) { response in
                    if response.voucherInfo.status == VoucherStatus.Active{
                        self.voucherInfo = response.voucherInfo
                        self.amount = Double(response.voucherInfo.amount)
                        
                        Util.notifyWhenTextWasChanged(textField: self.tfBarcode, color: UIColor.green)
                        self.createVoucherReceipt()
                        self.setButtonUseStatus(isEnabled: true)
                        self.setButtonPrintStatus(isEnabled: true)
                    }
                    else{
                        switch response.voucherInfo.status{
                        case VoucherStatus.Inactive?:
                            Util.GeneralAlert(viewController: self, message: String.init(format: Util.getString("VoucherInactive"), response.voucherInfo.voucherCode))
                        case VoucherStatus.Used?:
                            Util.GeneralAlert(viewController: self, message: String.init(format: Util.getString("VoucherUsed"), response.voucherInfo.voucherCode))
                        case VoucherStatus.ValidityNotStarted?:
                            Util.GeneralAlert(viewController: self, message: String.init(format: Util.getString("VoucherValidityNotStarted"), response.voucherInfo.voucherCode))
                        case VoucherStatus.Expired?:
                            Util.GeneralAlert(viewController: self, message: String.init(format: Util.getString("VoucherExpired"), response.voucherInfo.voucherCode))
                        case VoucherStatus.MaxUseCountExceeded?:
                            Util.GeneralAlert(viewController: self, message: String.init(format: Util.getString("VoucherMaxUsed"), response.voucherInfo.voucherCode))
                        case VoucherStatus.Disabled?:
                            Util.GeneralAlert(viewController: self, message: String.init(format: Util.getString("VoucherDisabled"), response.voucherInfo.generator.voucherGeneratorName))
                        default:
                            let msg = response.resultMessage + "(\(response.resultCode))"
                            Util.GeneralAlert(viewController: self, message: msg)
                        }
                        
                        Util.notifyWhenTextWasChanged(textField: self.tfBarcode, color: UIColor.red)
                        self.tvGiftCardReceipt.text = ""
                        self.setButtonUseStatus(isEnabled: false)
                        self.setButtonPrintStatus(isEnabled: false)
                    }
                }
            }
        }
    }
    
    func createVoucherReceipt(){
        var validityStartDateString = ""
        if let validityStartDate = voucherInfo.validityStartDate{
            validityStartDateString =  Util.DateToShortDateString(date: validityStartDate)
        }
        
        var activationDateString = ""
        if let activationTime = voucherInfo.activationTime{
            activationDateString =  Util.DateToShortDateString(date: activationTime)
        }
        
        if let status = voucherInfo.status{
            let status1 = String.init(format: Util.getString("VoucherSettingsLine1"), voucherInfo.voucherCode, Util.getString("\(status)"), activationDateString)
            self.tvGiftCardReceipt.text = status1
        }
        let status3 = String.init(format: Util.getString("VoucherSettingsLine3"), voucherInfo.voucherCode, voucherInfo.currencyId, Util.DoubleToStringWithTwoDecimals(Double(voucherInfo.amount)))
        
        if let validityEndDate = voucherInfo.validityEndDate{
            let validityEndDateString =  Util.DateToShortDateString(date: validityEndDate)
            let status2 = String.init(format: Util.getString("VoucherSettingsLine2"), validityStartDateString, validityEndDateString)
            
            self.tvGiftCardReceipt.text.append("\n")
            self.tvGiftCardReceipt.text.append(status2)
            
        }
        self.tvGiftCardReceipt.text.append("\n")
        self.tvGiftCardReceipt.text.append(status3)
        
        self.tvGiftCardReceipt.text.append("\n")
        self.tvGiftCardReceipt.text.append(voucherInfo.generator.message)
    }
    
    @IBAction func btPrintGiftCard_Click(_ sender: Any) {
        let footerMessage = self.createTicketFooter(ticketNumber: 0)
        self.tvGiftCardReceipt.text.append("\n\n")
        self.tvGiftCardReceipt.text.append(footerMessage)
        settings.printer?.printVoucherMessageNonFiscal(voucherMessage: self.tvGiftCardReceipt.text, completionHandler: { result in
            if result == false{
                Util.GeneralAlert(viewController: self, message: Util.getString("Receipt not printed!"))
            }
        })
        self.createVoucherReceipt()
    }
    
    func createTicketFooter(ticketNumber: Int) -> String {
        let line1 = String.init(format: "PDV.%@  C.%@", settings.StoreCode, settings.CashRegister)
        var line2 = ""
        if ticketNumber != 0 {
            if let userCode = settings.LoggedInUserCode{
                line2 = String.init(format: "TK.%@  OP.%@ \(Util.getString("Date")) %@", ticketNumber.description, userCode, Util.DateToShortDateString(date: Date()))
            }
        }
        else{
            if let userCode = settings.LoggedInUserCode{
                line2 = String.init(format: "OP.%@ \(Util.getString("Date")) %@", userCode, Util.DateToShortDateString(date: Date()))
            }
        }
        return line1 + "\n" + line2
    }
    
    @IBAction func btUseGiftCard_Click(_ sender: Any) {
        if self.canUseVoucher(){
            
            if let lotteryCode = State.lotteryCode, lotteryCode.isEmpty == false{
                if self.voucherInfo.salePaymentCategory != PaymentCategory.EFT
                    && self.voucherInfo.salePaymentCategory != PaymentCategory.BANK
                    && self.voucherInfo.salePaymentCategory != PaymentCategory.VOUCHER
                    && self.ticketType == .Receipt{
                    Util.alertWithTwoActions(viewController: self, title: Util.getString("Not allowed"), message: Util.getString("ConfirmDeleteLotteryCodePaymentCategoryCode"), firstActionTitle: Util.getString("Yes"), secondActionTitle: Util.getString("No")) {
                        // yes
                        State.lotteryCode = nil
                        self.processPaymentType()
                    } secondAction: {
                        // no
                        return
                    }
                }
                else{
                    self.processPaymentType()
                }
            }
            else{
                self.processPaymentType()
            }
        }
    }
    
    func processPaymentType(){
        var paymentType: String = PaymentTypeString.GIFT
        if let paymentTypeCode = self.voucherInfo.generator.paymentTypeCode{
            paymentType = paymentTypeCode
        }
        
        if let _paymentType = State.paymentType.first(where: { $0.Code == paymentType }){
            self.paymentType = _paymentType
            self.delegate.validatedVoucher(paymentType: self.paymentType, amount: self.amount, voucherInfo: self.voucherInfo)
        }
    }
    
    func canUseVoucher() -> Bool{
        if self.voucherInfo.amount == 0 {
            let msg = Util.getString("VoucherInvalidForPayment")
            Util.AlertOperationNotAllowed(viewController: self, message: msg)
            return false
        }
        
        for payment in self.payments{
            if payment.VoucherCode == self.voucherInfo.voucherCode{
                let msg = Util.getString("VoucherAlreadyAdded")
                Util.AlertOperationNotAllowed(viewController: self, message: msg)
                return false
            }
        }
        if voucherInfo.generator.cumulative == false{
            let msg = Util.getString("VoucherNonCumulative")
            Util.AlertOperationNotAllowed(viewController: self, message: msg)
            return false
        }
        if voucherInfo.generator.isScalable == false{
            if Double(voucherInfo.amount) > self.remainingValueToPay{
                let msg = Util.getString("VoucherValueGreaterThanValueToPay")
                Util.AlertOperationNotAllowed(viewController: self, message: msg)
                return false
            }
        }
        if voucherInfo.generator.voucherType != VoucherType.FIN{
            let msg = Util.getString("VoucherInvalidForPayment")
            Util.AlertOperationNotAllowed(viewController: self, message: msg)
            return false
        }
        
        return true
    }
    
    @IBAction func btCheckBarcode_Click(_ sender: Any) {
        self.checkBarcode()
    }
    
    @IBAction func btScanBarcode_Click(_ sender: Any) {
        let scannerViewController = self.storyboard?.instantiateViewController(withIdentifier: "scannerViewController") as! ScannerViewController
        scannerViewController.delegate = self
        scannerViewController.isSlideButtonVisible = false
        self.navigationController?.pushViewController(scannerViewController, animated: true)
    }
    
    func barcodeFound(barcode: String, captureSession: AVCaptureSession) {
        _ = self.navigationController?.popViewController(animated: true)
        self.tfBarcode.text = barcode
        self.checkBarcode()
    }
    
    func setButtonPrintStatus(isEnabled: Bool){
        self.btPrintGiftCard.isEnabled = isEnabled
        if isEnabled{
            self.btPrintGiftCard.setTitleColor(UIColor.init(white: 0.00, alpha: 1.00), for: .normal)
        }
        else{
            self.btPrintGiftCard.setTitleColor(UIColor.init(white: 0.00, alpha: 0.25), for: .normal)
        }
    }
    
    func setButtonUseStatus(isEnabled: Bool){
        self.btUseGiftCard.isEnabled = isEnabled
        if isEnabled{
            self.btUseGiftCard.setTitleColor(UIColor.init(white: 0.00, alpha: 1.00), for: .normal)
        }
        else{
            self.btUseGiftCard.setTitleColor(UIColor.init(white: 0.00, alpha: 0.25), for: .normal)
        }
    }
}
