//
//  TransactionStatusViewController.swift
//  iPOS
//
//  Created by BBC on 09/03/17.
//  Copyright © 2017 BBC. All rights reserved.
//

import Foundation

class TransactionStatusViewController: UIViewController, MasterViewControllerDelegate {
    
    @IBOutlet weak var statusTextLabel: UILabel!
    @IBOutlet weak var totalLabel: UILabel!
    @IBOutlet weak var createInvoiceButton: UIButton!
    @IBOutlet weak var cashLabel: UILabel!
    @IBOutlet weak var openReceiptButton: UIButton!
    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var contactLabel: UILabel!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var reprintReceipt: UIButton!
    
    var receiptId: String = ""
    var receipt: Receipt = Receipt()
    var isInvoiceIssued: Bool = false
    var isNewTransaction = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.showReprintButton()
    }
    
    func showReprintButton(){
        if settings.PrinterType != 1{
            self.reprintReceipt.isHidden = true
        }
        else{
            self.reprintReceipt.isHidden = false
            self.reprintReceipt.setTitle(Util.getString("Reprint"), for: .normal)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if self.isNewTransaction{
            self.createSkipButton()
            self.title = Util.getString("Payment successful")
            self.imageView.image = UIImage(named: "Transaction-Ok.png")
            self.navigationItem.setHidesBackButton(true, animated:true)
        }
        else{
            self.title = Util.getString("PaymentDetails")
            self.imageView.image = UIImage(named: "receiptDetails.png")
        }
        self.loadReceipt()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func loadReceipt(){
        State.loadReceiptForInvoice(receiptId: receiptId) { result in
            if let receipt = result{
                self.receipt = receipt
                self.statusTextLabel.text = Util.getString("Transaction no.") + " " + self.receipt.receiptNumber!.description
                let total = self.receipt.totalAmount! * Double(self.receipt.transactionSign!)
                self.totalLabel.text = Util.getString("Total") + " " + Util.DoubleToString(total) + settings.userSettings.defaultCurrency
                
                self.cashLabel.text = ""
                for receiptPayment in self.receipt.receiptPayments{
                    self.cashLabel.text?.append(receiptPayment.posPaymentTypes.Name + " " + Util.DoubleToString(receiptPayment.amount) + settings.userSettings.defaultCurrency)
                    self.cashLabel.text?.append("\n")
                }
                
                if let contact = self.receipt.contact {
                    if !contact.IsLegalPerson!{
                        self.contactLabel.text = contact.LastName + " " + contact.FirstName
                    }
                    else{
                        self.contactLabel.text = contact.FirstName
                    }
                }
                else{
                    self.contactLabel.text = nil
                }
                self.dateLabel.text = Util.DateToFullDateString(date: self.receipt.createTime)
                self.checkInvoice()
                self.checkReceiptType()
            }
            else{
                Util.AlertRetryAction(viewController: self, title: Util.getString("Error"), message: Util.getString("An error has occured."), actionOnRetry: self.loadReceipt, actionOnCancel: self.returnToShoppingCart)
            }
        }
    }
    
    func checkInvoice(){
        if self.receipt.invoiceNumber != nil{
            self.isInvoiceIssued = true
            self.createInvoiceButton.setTitle(Util.getString("Open invoice"), for: .normal)
        }
        else{
            self.isInvoiceIssued = false
            self.createInvoiceButton.setTitle(Util.getString("Create invoice"), for: .normal)
        }
    }
    
    func checkReceiptType(){
        if self.receipt.transactionSign == -1 { // Hide buttons for refund
            self.createInvoiceButton.isHidden = true
            self.openReceiptButton.isHidden = true
        }
        else{
            self.createInvoiceButton.isHidden = false
            self.openReceiptButton.isHidden = false
        }
    }
    
    func createSkipButton(){
        let skipButton = UIButton(type: .custom)
        skipButton.setTitle(Util.getString("Skip"), for: .normal)
        skipButton.setTitleColor(self.view.tintColor, for: .normal)
        skipButton.frame = CGRect(x: 0, y: 0, width: 50, height: 30)
        skipButton.addTarget(self, action: #selector(returnToShoppingCart), for: .touchUpInside)
        let skipButtonBarItem = UIBarButtonItem(customView: skipButton)
        self.navigationItem.rightBarButtonItem = skipButtonBarItem
    }
    
    @objc func returnToShoppingCart(){
        if let nc = self.navigationController {
            for i in 0..<nc.viewControllers.count{
                if (nc.viewControllers[i].isKind(of: ShoppingCartViewController.self)){
                    if  let viewController = self.navigationController?.viewControllers[i]{
                        _ = self.navigationController?.popToViewController(viewController, animated: false)
                        break
                    }
                    else{
                        _ = self.navigationController?.popViewController(animated: true)
                    }
                }
            }
        }else{
            _ = self.navigationController?.popViewController(animated: true)
        }
    }
    
    @IBAction func createInvoiceButton_Click(_ sender: Any) {
        if !self.isInvoiceIssued{
            let calendar = NSCalendar.current
            // *** Get components using current Local & Timezone ***
            let createdTimeComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: receipt.createTime)
            let currentTimeComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: Date())
            let daysDifference = currentTimeComponents.day! - createdTimeComponents.day!
            if daysDifference == 0{
                if self.receipt.hasLotteryCode{
                    Util.GeneralAlert(viewController: self, message: Util.getString("ReceiptHasLotteryCode"))
                    return
                }
                self.checkContact()
            }
            else{
                Util.GeneralAlert(viewController: self, message: Util.getString("The receipt was not created today."))
            }
        }
        else{
            self.goToInvoiceViewController()
        }
    }

    @IBAction func openReceiptButton_Click(_ sender: Any) {
        let invoiceViewController = (self.storyboard?.instantiateViewController(withIdentifier: "InvoiceViewController") as! InvoiceViewController)
        invoiceViewController.isInvoice = false
        invoiceViewController.receipt = self.receipt
        invoiceViewController.isNewInvoice = self.isNewTransaction
        self.navigationController?.pushViewController(invoiceViewController, animated: true)
    }
    
    func checkContact(){
        if(self.receipt.contact == nil){
            self.selectContact()
        }
        else if !(self.receipt.contact!.isValidForInvoicing()){
            self.requiredInfoAlert(title: "iPOS", message: Util.getString("This contact is missing info required for invoicing!"))
        }
        else{
            if self.receipt.contact!.IsLegalPerson != nil && (self.receipt.contact!.IsLegalPerson!) {
                if !self.receipt.contact!.isEIDestinationCodeMissing(){
                    Util.alertWithTwoActions(viewController: self, title: Util.getString("Warning"), message: Util.getString("DestinationCodeMissing"), firstActionTitle: Util.getString("Edit"), secondActionTitle: Util.getString("Continue anyway"), firstAction: {
                        self.goToEditViewController()
                    }) {
                        self.goToInvoiceViewController()
                    }
                }
                else{
                    if let vatCode = self.receipt.contact?.VatCode {
                        self.AlertInvoice(title: "iPOS", message: String.init(format: Util.getString("Are you sure that you want to create invoice for contact with vat code : %@?"),"\((vatCode))"), isContactVisible: false)
                    }
                    else{
                        self.AlertInvoice(title: "iPOS", message: Util.getString("Are you sure that you want to create invoice for this contact?"), isContactVisible: true)
                    }
                }
            }
            else {
                if let fiscalCode = self.receipt.contact?.FiscalCode {
                    self.AlertInvoice(title: "iPOS", message: String.init(format: Util.getString("Are you sure that you want to create invoice for contact with fiscal code : %@?"), "\((fiscalCode))"), isContactVisible: false)
                }
                else{
                    self.AlertInvoice(title: "iPOS", message: Util.getString("Are you sure that you want to create invoice for this contact?"), isContactVisible: true)
                }
            }
        }
    }

    func contactAlert(title: String, message: String)  {
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let CancelAction = UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler : { (action) -> Void in
            return
        })
        
        let CHangeContactAction = UIAlertAction(title: Util.getString("Change contact"), style: .default, handler : { (action) -> Void in
            self.selectContact()
        })
        
        let ContinueAction = UIAlertAction(title: Util.getString("Continue"), style: .default, handler : { (action) -> Void in
            self.goToInvoiceViewController()
        })
        
        alertController.addAction(ContinueAction)
        alertController.addAction(CHangeContactAction)
        alertController.addAction(CancelAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    func goToInvoiceViewController(){
        let invoiceViewController = (self.storyboard?.instantiateViewController(withIdentifier: "InvoiceViewController") as! InvoiceViewController)
        invoiceViewController.receipt = self.receipt
        invoiceViewController.isNewInvoice = self.isNewTransaction
        if self.isInvoiceIssued{
            invoiceViewController.isCreateInvoiceEnabled = false
        }
        self.navigationController?.pushViewController(invoiceViewController, animated: true)
    }
    
    func selectContact(){
        let masterViewController = (self.storyboard?.instantiateViewController(withIdentifier: "contactsViewController") as! MasterViewController)
        masterViewController.delegate = self
        masterViewController.isSlideButtonEnabled = false
        self.navigationController?.pushViewController(masterViewController, animated: true)
    }
    
    func selectedContactDelegate(contact: Contact){
        self.receipt.contact = contact
        if (self.receipt.contact?.isValidForInvoicing())!{
            if self.receipt.contact?.IsLegalPerson != nil && (self.receipt.contact?.IsLegalPerson!)! {
                if !self.receipt.contact!.isEIDestinationCodeMissing(){
                    Util.alertWithTwoActions(viewController: self, title: Util.getString("Warning"), message: Util.getString("DestinationCodeMissing"), firstActionTitle: Util.getString("Edit"), secondActionTitle: Util.getString("Continue anyway"), firstAction: {
                        self.goToEditViewController()
                    }) {
                        self.navigationController?.popViewController(animated: true)
                        self.goToInvoiceViewController()
                    }
                }
                else{
                    if let vatCode = self.receipt.contact?.VatCode {
                        self.AlertInvoice(title: "iPOS", message: String.init(format: Util.getString("Are you sure that you want to create invoice for contact with vat code : %@?"),"\((vatCode))"), isContactVisible: true)
                    }
                    else{
                        self.AlertInvoice(title: "iPOS", message: Util.getString("Are you sure that you want to create invoice for this contact?"), isContactVisible: true)
                    }
                }
            }
            else {
                if let fiscalCode = self.receipt.contact?.FiscalCode {
                    self.AlertInvoice(title: "iPOS", message: String.init(format: Util.getString("Are you sure that you want to create invoice for contact with fiscal code : %@?"), "\((fiscalCode))"), isContactVisible: true)
                }
                else{
                    self.AlertInvoice(title: "iPOS", message: Util.getString("Are you sure that you want to create invoice for this contact?"), isContactVisible: true)
                }
            }
        }
        else{
            self.requiredDataAlert(title: "iPOS", message: Util.getString("This contact is missing info required for invoicing!\nDo you want to edit the selected contact?"))
        }
    }
    
    func requiredDataAlert(title: String, message: String)  {
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let NoAction = UIAlertAction(title: "No", style: .default, handler : { (action) -> Void in
            self.receipt.contact = nil
        })
        
        let YesAction = UIAlertAction(title: Util.getString("Yes"), style: .default, handler : { (action) -> Void in
            self.goToEditViewController()
        })
        
        alertController.addAction(YesAction)
        alertController.addAction(NoAction)
        self.present(alertController, animated: true, completion: nil)
    }

    
    func requiredInfoAlert(title: String, message: String)  {
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let CancelAction = UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler : { (action) -> Void in
            return
        })
        
        let CHangeContactAction = UIAlertAction(title: Util.getString("Change contact"), style: .default, handler : { (action) -> Void in
            self.selectContact()
        })
        
        let EditContactAction = UIAlertAction(title: Util.getString("Edit contact"), style: .default, handler : { (action) -> Void in
            self.goToEditViewController()
        })
        
        alertController.addAction(EditContactAction)
        alertController.addAction(CHangeContactAction)
        alertController.addAction(CancelAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    func goToEditViewController(){
        if self.receipt.contact?.IsLegalPerson != nil{
            if (self.receipt.contact?.IsLegalPerson!)!{
                let editLegalPersonViewController = (self.storyboard?.instantiateViewController(withIdentifier: "EditLegalPersonViewController") as! EditLegalPersonViewController)
                editLegalPersonViewController.contact = self.receipt.contact
                editLegalPersonViewController.isNew = false
                self.navigationController?.pushViewController(editLegalPersonViewController, animated: true)
                return
            }
        }
        let editViewController = (self.storyboard?.instantiateViewController(withIdentifier: "editViewController") as! EditViewController)
        editViewController.contact = self.receipt.contact
        editViewController.isNew = false
        self.navigationController?.pushViewController(editViewController, animated: true)

    }
    
    func AlertInvoice(title: String, message: String, isContactVisible: Bool)  {
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let NoAction = UIAlertAction(title: Util.getString("No"), style: .default, handler : { (action) -> Void in
            self.receipt.contact = nil
        })
        
        let YesAction = UIAlertAction(title: Util.getString("Yes"), style: .default, handler : { (action) -> Void in
            if isContactVisible {
                self.navigationController?.popViewController(animated: true)
                self.goToInvoiceViewController()
            }
            else{
                self.goToInvoiceViewController()
            }
        })
        alertController.addAction(YesAction)
        alertController.addAction(NoAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    @IBAction func reprintReceipt_Click(_ sender: Any) {
        if settings.PrinterType != 1 {
            // Printer type 1 means epson non fiscal printer
            return
        }
        if let receiptLines = receipt.receiptLines, let receiptBarcode = receipt.receiptBarcode{
            settings.printer?.reprintReceipt(xml: receiptLines, barcode: receiptBarcode, completionHandler: { result in
                Util.GeneralAlert(viewController: self, message: Util.getString("ReceiptReprinted"))
            })
        }
    }
}
