//
//  ShoppingCartViewController.swift
//  iPOS
//
//  Created by bbc on 25/11/16.
//  Copyright © 2016 BBC. All rights reserved.
//

import UIKit
import AVFoundation

enum clientSelection: Int {
    case None = 0
    case FidelityCard = 1
    case Contact = 2
}

class ShoppingCartViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIPopoverPresentationControllerDelegate, ScannerViewControllerDelegate, MasterViewControllerDelegate, EditViewControllerDelegate, SearchBarcodeViewControllerDelegate, CartItemEditCustomCellDelegate, IProductSelectorListener, UIGestureRecognizerDelegate, PriceChangeDelegate, PaymentViewControllerDelegate, UITextFieldDelegate, FidelityCardControllerDelegate {

    @IBOutlet weak var lfNumberOfProducts: UILabel!
    @IBOutlet weak var buttonPayment: UIButton!
    @IBOutlet weak var buttonBarcodeScanner: UIButton!
    @IBOutlet weak var buttonBarcodeSearch: UIButton!
    @IBOutlet weak var buttonAddContactToTransaction: UIButton!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var lfSelectedContact: UILabel!
    @IBOutlet weak var buttomView: UIView!
    @IBOutlet weak var lfFidelityCard: UILabel!
    @IBOutlet weak var buttonFidelityCard: UIButton!
    @IBOutlet weak var btDiscount: UIButton!
    @IBOutlet weak var btAddNewItem: UIButton!
    @IBOutlet weak var btLotteryCode: UIButton!
    @IBOutlet weak var tfLotteryCode: UITextField!
    var isLotteryCodeScanned: Bool = false
    
    var quantity = [Double]()
    var shoppingCart: ShoppingCart?
    var scannerViewController: UIViewController!
    //var contactId: String?
    //var contact: Contact?
    var fiscalCode: String?
    var transactionCode: String?
    var indexToShow:Int?
    var indexToHide:Int?
    var ingenicoTransactionResponse: PTTransactionResult?
    var isBagButtonEnabled = true
    //var fidelityCard: FidelityCard?
    var isSlideButtonEnabled:Bool = true
    var promoCart: PromoShoppingCart = PromoShoppingCart()
    var electronicPayments: [Payment] = []
    let fakeTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
    var financialVoucherToActivate: VoucherInfo = VoucherInfo()
    var firstSelection: clientSelection = clientSelection.None
    var alert = UIAlertController()
    var ticketType: TicketType = TicketType.Receipt
    var financialVoucherToCreate: CreateVoucherRequest = CreateVoucherRequest()
    
    var allowProcessFidelityAfterContact: Bool{
        get{
            return settings.storeSetupSettings.clientName.uppercased() != "NAU!" || self.firstSelection != clientSelection.FidelityCard
        }
    }
    
    var allowProcessContactAfterFidelity: Bool{
        get{
            return settings.storeSetupSettings.clientName.uppercased() != "NAU!" || self.firstSelection == clientSelection.None
        }
    }
    
    var allowDownloadContactOnProcessFidelity: Bool{
        get{
            return settings.storeSetupSettings.clientName.uppercased() == "NAU!" && self.firstSelection == clientSelection.None
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.addScrollTapGesture()
        self.addDelegates()
    }
    
    func addDelegates(){
        self.tableView.delegate = self
        self.popoverPresentationController?.delegate = self
        self.fakeTextField.delegate = self
        self.tfLotteryCode.delegate = self
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.indexToHide = nil
        self.indexToShow = nil
        for item in State.shoppingCart.cartItems{
            if item.Quantity != self.quantity[item.RowNumber - 1]{
                self.quantity[item.RowNumber - 1] = item.Quantity
                State.shoppingCart.recalculate(){
                    self.refreshShoppingCartTotals()
                    return
                }
            }
        }
    }
    
    override func setEditing(_ editing: Bool, animated: Bool) {
        super.setEditing(editing, animated: animated)
        self.tableView.setEditing(editing, animated: animated)
    }
    
    func refreshShoppingCartTotals(){
        let numberOfProducts = self.productAddedCount()
        if(numberOfProducts == 0){
            self.lfNumberOfProducts.text = "\(numberOfProducts.description) " + Util.getString("Products")
            self.buttonPayment.isEnabled = false
        }
        else if(numberOfProducts == 1){
            self.lfNumberOfProducts.text = "\(numberOfProducts.description) " + Util.getString("Product")
            if tableView.indexPathsForSelectedRows == nil{
                self.buttonPayment.isEnabled = true
            }
        }
        else if (numberOfProducts > 1){
            self.lfNumberOfProducts.text = "\(numberOfProducts.description) " + Util.getString("Products")
            if tableView.indexPathsForSelectedRows == nil{
                self.buttonPayment.isEnabled = true
            }
        }
        
        self.btDiscount.setTitle(Util.getString("Disc.") + " \(Util.DoubleToString(State.shoppingCart.getTotalDistributedDiscount()))" + "\(settings.userSettings.defaultCurrency)", for: .normal)
        
        if(State.shoppingCart.netValue >= 0){
            let customGreen = UIColor(red: 0.043137254901960784, green: 0.63921568627450975, blue: 0.0, alpha: 1)
            self.buttonPayment.backgroundColor = customGreen
            self.buttonPayment.setTitle(Util.getString("Pay") + " \(Util.DoubleToString(State.shoppingCart.netValue))" + "\(settings.userSettings.defaultCurrency)", for: .normal)
        }else{
            self.buttonPayment.backgroundColor = UIColor.red
            self.buttonPayment.setTitle(Util.getString("Refund") + " \(Util.DoubleToString(State.shoppingCart.netValue))" + "\(settings.userSettings.defaultCurrency)", for: .normal)
        }
        
        self.tableView.reloadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.changeButtonsStatus(true)

        if self.isSlideButtonEnabled{
            self.setNavigationBarItem()
        }
        else{
            self.removeNavigationBarItem()
        }
        
        if let contact = State.shoppingCart.contact{
            self.selectedContactFromReceipt(contact: contact)
        }
        
        self.navigationItem.title = Util.getString("Shopping Cart")
        self.navigationItem.rightBarButtonItem = editButtonItem
        
        State.LoadPaymentTypes(completionHandler: {result in })
        self.quantity.removeAll()
        self.setQuantityArray()
        self.isBagButtonEnabled = true
        self.electronicPayments = []
        
        self.refreshShoppingCartTotals()
        State.shoppingCart.isItemAdded = nil
        State.shoppingCart.recalculate(){
            self.refreshShoppingCartTotals()
        }
        self.fakeTextFieldSimulateEditing()
        
        self.manageCustomLayout()
        
        self.btLotteryCode.isHidden = true
        self.tfLotteryCode.isHidden = true
        self.tfLotteryCode.text = ""
        
        if State.isLotteryActive{
            self.setLotteryCodePlaceholder()
            self.btLotteryCode.isHidden = false
            self.tfLotteryCode.isHidden = false
            if let lotteryCode = State.lotteryCode{
                self.tfLotteryCode.text = lotteryCode
            }
        }
    }
    
    func setLotteryCodePlaceholder(){
        self.tfLotteryCode.placeholder = " Codice Lotteria"
        if let text = self.tfLotteryCode.placeholder{
            let height =  self.tfLotteryCode.frame.height
            let size: CGSize = text.size(withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12)])
           
            let label = UILabel(frame: CGRect(x: 0, y: 0, width: size.width, height: height))
            label.font = UIFont.systemFont(ofSize: 12)
            label.textAlignment = NSTextAlignment.right
            label.textColor = UIColor(red: 0.78, green: 0.78, blue: 0.80, alpha: 1.0)
            label.text = text
            self.tfLotteryCode.placeholder = nil
            self.tfLotteryCode.leftView = label
            self.tfLotteryCode.leftViewMode = .unlessEditing
        }
    }
    
    func manageCustomLayout(){
        self.btLotteryCode.layer.cornerRadius = 10
        self.btLotteryCode.layer.borderWidth = 1
        self.btLotteryCode.layer.borderColor = UIColor.lightGray.cgColor
        self.btLotteryCode.layer.backgroundColor = UIColor.lightGray.cgColor
        self.btLotteryCode.backgroundColor = UIColor.white
        self.btLotteryCode.layer.shadowColor = UIColor.black.cgColor
        self.btLotteryCode.layer.shadowOffset = CGSize(width: 0, height: 1.0)
        self.btLotteryCode.layer.shadowOpacity = 0.5
        self.btLotteryCode.layer.shadowRadius = 10
    
        self.tfLotteryCode.layer.cornerRadius = 10
        self.tfLotteryCode.layer.borderWidth = 1
        self.tfLotteryCode.layer.borderColor = UIColor.lightGray.cgColor
        self.tfLotteryCode.layer.backgroundColor = UIColor.lightGray.cgColor
        self.tfLotteryCode.backgroundColor = UIColor.white
        self.tfLotteryCode.layer.shadowColor = UIColor.black.cgColor
        self.tfLotteryCode.layer.shadowOffset = CGSize(width: 0, height: 1.0)
        self.tfLotteryCode.layer.shadowOpacity = 0.5
        self.tfLotteryCode.layer.shadowRadius = 10

        self.btDiscount.layer.shadowColor = UIColor.black.cgColor
        self.btDiscount.layer.shadowOffset = CGSize(width: 0, height: 1.0)
        self.btDiscount.layer.shadowOpacity = 0.5
        
        self.buttonPayment.layer.shadowColor = UIColor.black.cgColor
        self.buttonPayment.layer.shadowOffset = CGSize(width: 0, height: 1.0)
        self.buttonPayment.layer.shadowOpacity = 0.5
    }
    
    func selectedContactFromReceipt(contact: Contact){
        State.shoppingCart.contact = contact
        if contact.FidelityCard != nil && State.shoppingCart.fidelityCard == nil{
            State.shoppingCart.fidelityCard = contact.FidelityCard
            if let fidelityCard = State.shoppingCart.fidelityCard{
                self.getFidelityCardInfo(fidelityCard: fidelityCard)
            }
        }
        self.setLabelForSelectedContact()
        State.contactFiscalCodeForTransaction = contact.FiscalCode
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        if (self.isMovingFromParent){
            AppDelegate.leftViewController.shoppingCartView.isSlideButtonEnabled = true
            AppDelegate.leftViewController.shoppingCartViewController = UINavigationController(rootViewController: AppDelegate.leftViewController.shoppingCartView)
        }
    }
    
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func setQuantityArray(){
        for item in State.shoppingCart.cartItems{
            self.quantity.append(item.Quantity)
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return State.shoppingCart.cartItems.count * 2
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        if self.indexToHide != nil || self.indexToShow != nil{
            if self.indexToHide != nil{
                if self.indexToHide == indexPath.row{
                    self.indexToHide = nil
                    return 0.0
                }
            }
            if self.indexToShow != nil{
                if self.indexToShow == indexPath.row{
                    return 40.0
                }
            }
            if ((indexPath.row % 2) != 0){
                return 0.0
            }
        }
        else if ((indexPath.row % 2) != 0){
            return 0.0
        }
        return 72.0
    }
    
    func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath?{
        if ((indexPath.row % 2) == 0){
            return indexPath
        }
        return nil
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        if ((tableView.indexPathsForSelectedRows == nil) && ((indexPath.row % 2) == 0)) {
            self.changeButtonsStatus(true)
            return true
        }
        return false
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if (indexPath.row % 2) == 0 || indexPath.row == 0 {
            let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell")! as! CartItemCustomCell
            let cartItem = State.shoppingCart.cartItems[indexPath.row / 2]
        
            if(cartItem.barcodeInfo.ImageIcon == nil){
                cell.imageIcon.image = UIImage(named: "defaultProduct.png")
            }
            else{
                cell.imageIcon.image = cartItem.barcodeInfo.ImageIcon
            }
            
            cell.productName.text = cartItem.barcodeInfo.Name
            cell.productCode.text = cartItem.barcodeInfo.Code
            
            if let sn = cartItem.serialNumber {
                cell.productCode.text?.append(" - \(sn)")
            }
            
            cell.quantityVar = cartItem.Quantity
            cell.quantity.text = cartItem.Quantity.description + " x "
            let netRowValue = Util.DoubleToStringWithPointSeparator(cartItem.NetRowValue)
            let grossRowValue = Util.DoubleToStringWithPointSeparator(cartItem.GrossUnitValue * cartItem.Quantity)
            if((Double(netRowValue)?.isLess(than: (Double(grossRowValue)!)))! || cartItem.PromotionId != nil){
                let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: Util.DoubleToString(cartItem.GrossUnitValue) + " \(settings.userSettings.defaultCurrency)")
                attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length))
                cell.grossUnitValue.attributedText = attributeString
                cell.netRowValue.textColor = UIColor.red
            
                cell.productName.textColor = UIColor.black
                cell.productCode.textColor = UIColor.black
                cell.quantity.textColor = UIColor.black
                cell.grossUnitValue.textColor = UIColor.black
                cell.sizeCode.textColor = UIColor.black
                cell.productColor.textColor = UIColor.black
            }
            else{
                cell.grossUnitValue.attributedText = nil
                cell.grossUnitValue.text = Util.DoubleToString(cartItem.GrossUnitValue) + " \(settings.userSettings.defaultCurrency)"
                
                if cell.quantityVar < 0{
                    cell.productName.textColor = UIColor.red
                    cell.productCode.textColor = UIColor.red
                    cell.quantity.textColor = UIColor.red
                    cell.grossUnitValue.textColor = UIColor.red
                    cell.netRowValue.textColor = UIColor.red
                    cell.sizeCode.textColor = UIColor.red
                    cell.productColor.textColor = UIColor.red
                    
                }else{
                    cell.productName.textColor = UIColor.black
                    cell.productCode.textColor = UIColor.black
                    cell.quantity.textColor = UIColor.black
                    cell.grossUnitValue.textColor = UIColor.black
                    cell.netRowValue.textColor = UIColor.black
                    cell.sizeCode.textColor = UIColor.black
                    cell.productColor.textColor = UIColor.black
                }
            }
            cell.netRowValue.text = Util.DoubleToString(cartItem.NetRowValue) + " \(settings.userSettings.defaultCurrency)"
            cell.sizeCode.text = cartItem.barcodeInfo.SizeCode
            cell.productColor.text = cartItem.barcodeInfo.ColorName
            return cell
        }
        else{
            let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell2")! as! CartItemEditCustomCell
            cell.rowNumber = indexPath.row
            cell.delegate = self
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            State.shoppingCart.removeItem(at: indexPath.row / 2)
            self.quantity.remove(at: indexPath.row / 2)
            var index = indexPath
            index.row += 1
            tableView.deleteRows(at: [index, indexPath], with: .fade)
            State.shoppingCart.recalculate(){
                self.refreshShoppingCartTotals()
            }
        }
    }
    
    func minusButtonAction(rowNumber: Int?) {
        if let row = rowNumber{
            if let indexPaths = tableView.indexPathsForSelectedRows{
                for indexPath in indexPaths{
                    let cell = tableView.cellForRow(at: indexPath)! as! CartItemCustomCell
                    
                    let cartItem = State.shoppingCart.cartItems[indexPath.row / 2]
                    
                    if let decimalPlaces = cartItem.barcodeInfo.DecimalPlaces, decimalPlaces > 0 {
                        if cartItem.Quantity > 0 {
                            cartItem.Quantity = cartItem.Quantity * (-1)
                            cell.quantityVar = cartItem.Quantity
                            cell.quantity.text = cell.quantityVar.description + " x "
                        }
                        return
                    }
                    
                    if cartItem.barcodeInfo.hasSerialNumber{
                        cell.quantityVar = -1
                        cell.quantity.text = cell.quantityVar.description + " x "
                        if !cartItem.canApplyPromotions{
                            cartItem.DiscountValue -= cartItem.DiscountValue / cartItem.Quantity
                        }
                        cartItem.Quantity = -1
                        State.shoppingCart.lastItemRemoved = cartItem
                        State.shoppingCart.isItemAdded = false
                        
                        return
                    }
                    
                    if cell.quantityVar == 1{
                        // skip setting quantity to 0(jump from 1 to -1
                        cell.quantityVar = -1
                        cartItem.Quantity = -1
                        
                        if indexPath.row + 1 == row{
                            cell.quantity.text = cell.quantityVar.description + " x "
                            if !cartItem.canApplyPromotions{
                                cartItem.DiscountValue = cartItem.DiscountValue * (-1)
                            }
                            State.shoppingCart.lastItemRemoved = cartItem
                            State.shoppingCart.isItemAdded = false
                        }
                    }
                    else{
                        if indexPath.row + 1 == row{
                            cell.quantityVar -= 1
                            cell.quantity.text = cell.quantityVar.description + " x "
                            if !cartItem.canApplyPromotions{
                                if cartItem.Quantity < 0 {
                                    cartItem.DiscountValue -= (abs(cartItem.DiscountValue) / abs(cartItem.Quantity))
                                }
                                else{
                                    cartItem.DiscountValue -= cartItem.DiscountValue / cartItem.Quantity
                                }
                            }
                            cartItem.Quantity -= 1
                            State.shoppingCart.lastItemRemoved = cartItem
                            State.shoppingCart.isItemAdded = false
                        }
                    }
                }
            }
        }
    }
    
    func plusButtonAction(rowNumber: Int?) {
        if let row = rowNumber{
            if let indexPaths = tableView.indexPathsForSelectedRows{
                for indexPath in indexPaths{
                    let cell = tableView.cellForRow(at: indexPath)! as! CartItemCustomCell
                    
                    let cartItem = State.shoppingCart.cartItems[indexPath.row / 2]
                    
                    if let decimalPlaces = cartItem.barcodeInfo.DecimalPlaces, decimalPlaces > 0 {
                        if cartItem.Quantity < 0 {
                            cartItem.Quantity = cartItem.Quantity * (-1)
                            cell.quantityVar = cartItem.Quantity
                            cell.quantity.text = cell.quantityVar.description + " x "
                        }
                        return
                    }
                    
                    if cartItem.barcodeInfo.hasSerialNumber{
                        cell.quantityVar = +1
                        cell.quantity.text = cell.quantityVar.description + " x "
                        if !cartItem.canApplyPromotions{
                            cartItem.DiscountValue += cartItem.DiscountValue / cartItem.Quantity
                        }
                        cartItem.Quantity = +1
                        State.shoppingCart.lastItemAdded = cartItem
                        State.shoppingCart.isItemAdded = true
                        
                        return
                    }
                    
                    if cell.quantityVar == -1{
                        // skip setting quantity to 0(jump from -1 to 1
                        cell.quantityVar = 1
                        cartItem.Quantity = 1
                        
                        if indexPath.row + 1 == row{
                            cell.quantity.text = cell.quantityVar.description + " x "
                            if !cartItem.canApplyPromotions{
                                cartItem.DiscountValue = abs(cartItem.DiscountValue)
                            }
                            State.shoppingCart.lastItemAdded = cartItem
                            State.shoppingCart.isItemAdded = true
                        }
                    }
                    else{
                        if indexPath.row + 1 == row{
                            cell.quantityVar += 1
                            cell.quantity.text = cell.quantityVar.description + " x "
                            if !cartItem.canApplyPromotions{
                                if cartItem.Quantity < 0 {
                                    cartItem.DiscountValue += (abs(cartItem.DiscountValue) / abs(cartItem.Quantity))
                                }
                                else{
                                    cartItem.DiscountValue += cartItem.DiscountValue / cartItem.Quantity
                                }
                            }
                            cartItem.Quantity += 1
                            State.shoppingCart.lastItemAdded = cartItem
                            State.shoppingCart.isItemAdded = true
                        }
                    }
                }
            }
        }
    }
    
    func displayButtonAction(rowNumber: Int?) {
        if let row = rowNumber{
            if let indexPaths = tableView.indexPathsForSelectedRows{
                for indexPath in indexPaths{
                    if tableView.cellForRow(at: indexPath) != nil{
                        if indexPath.row + 1 == row{
                            let cartItem = State.shoppingCart.cartItems[indexPath.row / 2]
                            let tempShoppingCart = ShoppingCart()
                            tempShoppingCart.addItem(barcodeInfo: cartItem.barcodeInfo.clone())
                            tempShoppingCart.recalculate(completionHandler: {
                                let productDetailViewController = (self.storyboard?.instantiateViewController(withIdentifier: "productDetailViewController") as! ProductDetailViewController)
                                productDetailViewController.delegate = self
                                self.isBagButtonEnabled = false
                                productDetailViewController.cartItem = tempShoppingCart.cartItems[0]
                                self.navigationController?.pushViewController(productDetailViewController, animated: true)
                            })
                        }
                        else{
                            NetworkController.AlertConnectionError(viewController: self)
                        }
                    }
                }
            }
        }
    }
    
    func discountButtonAction(rowNumber: Int?){
        let rowIndex = (rowNumber! - 1) / 2
        let cartItem = State.shoppingCart.cartItems[rowIndex]
        if self.quantity[rowIndex] != cartItem.Quantity{
            self.quantity[rowIndex] = cartItem.Quantity
            State.shoppingCart.recalculate(){
                self.refreshShoppingCartTotals()
                self.indexToHide = nil
                self.indexToShow = rowNumber!
                let indexPath = NSIndexPath(row: rowNumber! - 1, section: 0)
                self.tableView.selectRow(at: indexPath as IndexPath, animated: true, scrollPosition: .none)
                self.tableView.beginUpdates()
                self.tableView.endUpdates()
                self.changeDiscount(rowNumber: rowNumber)
            }
        }
        else{
            self.changeDiscount(rowNumber: rowNumber)
        }
    }
    
    func openPopUp(_ dataSource: [INameable], _ dataSourceType: String, _ title: String ) {
        let popupSelectorViewController = self.storyboard?.instantiateViewController(withIdentifier: "popupSelectorViewController") as! PopupSelectorViewController
        popupSelectorViewController.shouldBeSearchBarHidden = false
        popupSelectorViewController.itemSelectedCallback = selectedValue
        popupSelectorViewController.dataSource = dataSource
        popupSelectorViewController.dataSourceType = dataSourceType
        popupSelectorViewController.title = title
        let nav = UINavigationController(rootViewController: popupSelectorViewController)
        nav.modalPresentationStyle = UIModalPresentationStyle.fullScreen
        self.present(nav, animated: true, completion: nil)
    }
    
    func selectedValue(item: AnyObject, parentItem: AnyObject?){
        if item.isKind(of: DiscountCauses.self){
            let discountCause = item as! DiscountCauses
            if let cartItem = self.changeDiscountForItem{
                let item: PriceChangeItem = cartItem.convertToPriceChangeItem()
                item.discountCause = discountCause
                if(discountCause.isFixedDiscount){
                    self.applyFixedDiscount(item: item, discountCause: discountCause)
                }
                else{
                    let dialog: PriceChangeDialog = PriceChangeDialog(item: item, delegate: self)
                    dialog.show(viewController: self)
                }
            }
        }
    }
    
    func applyFixedDiscount(item: PriceChangeItem, discountCause: DiscountCauses){
        let result: PriceChangeResult = PriceChangeResult(item: item)
        result.discountCause = discountCause
        
        let discountValue = item.grossUnitValue - Util.applyDiscount(grossValue: item.grossUnitValue, discountPercent: discountCause.maxDiscount)
        let newPrice = (item.grossUnitValue - discountValue).rounded(toPlaces: 2)
        
        if item.grossUnitValue >= newPrice{
            result.netRowValueVatIncluded = newPrice
        }
        else{
            result.grossUnitValueVatIncluded = newPrice
        }
        result.discountValue = discountValue * item.quantity
        result.discountPercentage = Double(discountCause.maxDiscount * 100).rounded(toPlaces: 2)
        result.effectCategory = "PD%"
        result.canApplyPromotions = false
        
        self.handlePriceChangeResult(result: result)
    }
    
    var changeDiscountForItem: ShoppingCartItem? = nil
    func changeDiscount(rowNumber: Int?){
        if let row = rowNumber, let indexPaths = tableView.indexPathsForSelectedRows{
            for indexPath in indexPaths{
                if tableView.cellForRow(at: indexPath) != nil && indexPath.row + 1 == row{
                    State.loadDiscountCauses(filterString: nil, completionHandler: { result in
                        if let discountCauses = result {
                            self.changeDiscountForItem = State.shoppingCart.cartItems[indexPath.row / 2]
                            self.openPopUp(discountCauses, "DiscountCauses", "Discount Causes")
                        }
                    })
                }
            }
        }
    }
    
    func onApplay(result: PriceChangeResult) {
        self.handlePriceChangeResult(result: result)
    }
    
    func onClear(result: PriceChangeResult) {
        self.handlePriceChangeResult(result: result)
    }
    
    func onCancel() {
        return
    }
    
    func handlePriceChangeResult(result: PriceChangeResult){
        let cartItem = State.shoppingCart.cartItems[result.rowNumber - 1]
        cartItem.importPriceChanges(result: result)
        cartItem.addEffect(discountCause: result.discountCause, rowNumber: result.rowNumber, discountValue: result.discountValue, discountPercentage: result.discountPercentage, effectCategory: result.effectCategory)
        
        if self.quantity[result.rowNumber - 1] != cartItem.Quantity{
            self.quantity[result.rowNumber - 1] = cartItem.Quantity
        }
        State.shoppingCart.recalculate(){
            self.refreshShoppingCartTotals()
            self.indexToHide = (result.rowNumber - 1) * 2 + 1
            self.indexToShow = nil
            self.tableView.beginUpdates()
            self.tableView.endUpdates()
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        if let indexPaths = tableView.indexPathsForSelectedRows{
            for index in indexPaths{
                if index != indexPath{
                    self.indexToHide = index.row + 1
                    tableView.deselectRow(at: index, animated: false)
                    if quantity[index.row / 2] != State.shoppingCart.cartItems[index.row / 2].Quantity{
                        self.quantity[index.row / 2] = State.shoppingCart.cartItems[index.row / 2].Quantity
                        State.shoppingCart.recalculate(){
                            self.refreshShoppingCartTotals()
                            self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
                            tableView.beginUpdates()
                            tableView.endUpdates()
                        }
                    }
                }
            }
        }
        
        self.indexToShow = indexPath.row + 1
        tableView.beginUpdates()
        tableView.endUpdates()
        self.changeButtonsStatus(false)
    }
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        if quantity[indexPath.row / 2] != State.shoppingCart.cartItems[indexPath.row / 2].Quantity{
            self.quantity[indexPath.row / 2] = State.shoppingCart.cartItems[indexPath.row / 2].Quantity
            State.shoppingCart.recalculate(){
                self.refreshShoppingCartTotals()
            }
        }
        if tableView.indexPathsForSelectedRows == nil{
            self.indexToHide = indexPath.row + 1
            self.indexToShow = nil
            tableView.beginUpdates()
            tableView.endUpdates()
            self.changeButtonsStatus(true)
        }
    }
    
    func trySaveTransaction(){
        self.promoCart.receiptLines = State.shoppingCart.receiptLines
        if State.shoppingCart.payments[0].paymentType.Code==PaymentTypeString.CR
        {
            self.promoCart.issuedVoucherCode = State.shoppingCart.payments[0].VoucherCode
        }
        State.SaveShoppingCartTransaction(promoCart: self.promoCart, completionHandler: {result in
            if (result.resultCode == -1) {
                Util.GeneralAlertWithAction(viewController: self, message: Util.getString("Could not save the transaction, check your connection and try again later."), generalAction: self.onFailureEndPayment)
                Util.writeLogCustom(eventName: "save_payment", name: "Payment", text: "Could not save the transaction, check your connection and try again later.")
                return
            }
            else if (result.resultCode == 1) {
                Util.GeneralAlertWithAction(viewController: self, message: result.resultMessage, generalAction: self.onFailureEndPayment)
                Util.writeLogCustom(eventName: "save_payment", name: "Payment", text: result.resultMessage)
                return
            }
            else if (result.resultCode == 2) {
                let msg = result.resultMessage + " " + result.resultErrorDetails
                Util.GeneralAlertWithAction(viewController: self, message: msg, generalAction: self.onFailureEndPayment)
                Util.writeLogCustom(eventName: "save_payment", name: "Payment", text: msg)
                return
            }
            else{
                self.endPayment()
                
                Util.writeLogCustom(eventName: "save_payment", name: "Payment", text: "Transaction succeeded - \(result.transactionId) [\(result.transactionNumber)]")
            }
        })
    }
    
    func beginPayment(){
        if settings.FiscalDocumentType == 0{
            //Receipt
           self.tryPrintReceipt()
        }
        else{
            //Invoice
            self.trySaveTransaction()
        }
    }
    
    func endPayment(){
        if settings.FiscalDocumentType == 0{
            //Receipt
            if self.promoCart.receiptType == "F"{
                self.renewShoppingCart()
                self.returnToShoppingCart()
            }
            else{
                self.renewShoppingCart()
                self.LoadTransactionStatusViewController()
            }
        }
        else{
            //Invoice
            self.renewShoppingCart()
            self.goToInvoiceViewController()
        }
    }
    
    func resetContact(){
        State.shoppingCart.contact = nil
        State.contactFiscalCodeForTransaction = nil
        self.lfSelectedContact.text = Util.getString("No contact selected")
        self.resetFidelityCard()
        
        State.shoppingCart.recalculate {
            self.refreshShoppingCartTotals()
        }
    }
    
    func resetFidelityCard(){
        self.lfFidelityCard.text = Util.getString("No fidelity card")
        State.shoppingCart.fidelityCard = nil
        if State.shoppingCart.usedPoints != nil{
            State.shoppingCart.applyFidelityPointsDiscount(usedPoints: nil, discountValue: nil)
            State.shoppingCart.recalculate {
                self.refreshShoppingCartTotals()
            }
        }
        
        self.firstSelection = .None
    }
    
    func goToInvoiceViewController(){
        if let receiptId = State.transactionId{
            let invoiceViewController = (self.storyboard?.instantiateViewController(withIdentifier: "InvoiceViewController") as! InvoiceViewController)
            invoiceViewController.receiptId = receiptId.description
            self.fiscalCode = nil
            self.shoppingCart = nil
            self.navigationController?.pushViewController(invoiceViewController, animated: true)
        }
    }
    
    func AlertInvoice(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.resetContact()
        })
        
        let YesAction = UIAlertAction(title: Util.getString("Yes"), style: .default, handler : { (action) -> Void in
            _ = self.navigationController?.popViewController(animated: true)
        })
        alertController.addAction(YesAction)
        alertController.addAction(NoAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    
    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.resetContact()
        })
        
        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 AlertContact(title: String, message: String, flag: String)  {
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let OkAction = UIAlertAction(title: "Ok", style: .default, handler : { (action) -> Void in
            if (flag == "select"){
                self.goToMasterViewController()
            }
            else if flag == "edit"{
                self.goToEditViewController()
            }
        })
        alertController.addAction(OkAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    func goToMasterViewController(){
        let masterViewController = (self.storyboard?.instantiateViewController(withIdentifier: "contactsViewController") as! MasterViewController)
        masterViewController.isSlideButtonEnabled = false
        masterViewController.delegate = self
        self.navigationController?.pushViewController(masterViewController, animated: true)
    }
    
    func goToDetailViewController(contact: Contact){
        if let isLegalPerson = contact.IsLegalPerson{
            if isLegalPerson{
                var legalPersonDetailViewController = self.storyboard?.instantiateViewController(withIdentifier: "LegalPersonDetailViewController") as! LegalPersonDetailViewController
                
                let vc = Util.getViewControllerFromStack(navigationController: self.navigationController, viewController: legalPersonDetailViewController)
                if let viewController = vc {
                    legalPersonDetailViewController = viewController as! LegalPersonDetailViewController
                    legalPersonDetailViewController.contact = contact
                    legalPersonDetailViewController.navigationItem.leftItemsSupplementBackButton = true
                    self.navigationController?.popToViewController(legalPersonDetailViewController, animated: true)
                }
                else{
                    legalPersonDetailViewController.contact = contact
                    legalPersonDetailViewController.navigationItem.leftItemsSupplementBackButton = true
                    self.navigationController?.pushViewController(legalPersonDetailViewController, animated: true)
                }
            }
            else{
                var detailViewController = self.storyboard?.instantiateViewController(withIdentifier: "detailViewController") as! DetailViewController
                
                let vc = Util.getViewControllerFromStack(navigationController: self.navigationController, viewController: detailViewController)
                if let viewController = vc {
                    detailViewController = viewController as! DetailViewController
                    detailViewController.contact = contact
                    detailViewController.navigationItem.leftItemsSupplementBackButton = true
                    self.navigationController?.popToViewController(detailViewController, animated: true)
                }
                else{
                    detailViewController.contact = contact
                    detailViewController.navigationItem.leftItemsSupplementBackButton = true
                    self.navigationController?.pushViewController(detailViewController, animated: true)
                }
            }
        }
        else{
            Util.GeneralAlert(viewController: self, message: "Could not open the details of the selected contact")
        }
    }
    
    func goToEditViewController(){
        if State.shoppingCart.contact?.IsLegalPerson != nil{
            if (State.shoppingCart.contact?.IsLegalPerson!)! {
                let editLegalPersonViewController = (self.storyboard?.instantiateViewController(withIdentifier: "EditLegalPersonViewController") as! EditLegalPersonViewController)
                editLegalPersonViewController.contact = State.shoppingCart.contact
                editLegalPersonViewController.isNew = false
                self.navigationController?.pushViewController(editLegalPersonViewController, animated: true)
                return
            }
        }
        let editViewController = (self.storyboard?.instantiateViewController(withIdentifier: "editViewController") as! EditViewController)
        editViewController.contact = State.shoppingCart.contact
        editViewController.isNew = false
        self.navigationController?.pushViewController(editViewController, animated: true)
    }
    
    func changeButtonsStatus(_ status: Bool){
        self.buttonPayment.isEnabled = status
        self.buttonAddContactToTransaction.isEnabled = status
        self.buttonBarcodeSearch.isEnabled = status
        self.buttonBarcodeScanner.isEnabled = status
        self.buttonFidelityCard.isEnabled = status
        self.navigationItem.rightBarButtonItem?.isEnabled = status
    }
    
    func LoadTransactionStatusViewController(){
        if let receiptId = State.transactionId{
            let transactionStatusViewController = self.storyboard?.instantiateViewController(withIdentifier: "TransactionStatusViewController") as! TransactionStatusViewController
            transactionStatusViewController.receiptId = receiptId.description
            self.fiscalCode = nil
            self.shoppingCart = nil
            self.navigationController?.pushViewController(transactionStatusViewController, animated: true)
        }
    }
    
    func tryPrintReceipt(){
        settings.printer?.printShoppingCart(State.shoppingCart,completionHandler: {result in
            if(result == true){
                Util.writeLogCustom(eventName: "print_ticket", name: "Receipts", text: "Receipt printed : \(State.receiptFiscalNumber).Try save transaction.")
                self.promoCart.receiptFiscalNumber = State.receiptFiscalNumber
                self.promoCart.zReportNumber = State.zReportNumber
                self.promoCart.fiscalPrinterSN = State.fiscalPrinterSN
                self.trySaveTransaction()
            }
            else if(result == false){
                Util.writeLogCustom(eventName: "print_ticket", name: "Receipts", text: "Error print.Receipt not printed!")
                Util.AlertRetryAction(viewController: self, title: Util.getString("Something went wrong"), message: Util.getString("Receipt not printed!"), actionOnRetry: self.tryPrintReceipt, actionOnCancel: nil)
            }
            else if(result == nil){
                Util.writeLogCustom(eventName: "print_ticket", name: "Receipts", text: "Error print.No network connection!")
                Util.AlertRetryAction(viewController: self, title: Util.getString("Something went wrong"), message: Util.getString("Receipt not printed!"), actionOnRetry: self.tryPrintReceipt, actionOnCancel: nil)
            }
        })
        if(settings.printer == nil){
            Util.writeLogCustom(eventName: "print_ticket", name: "Receipts", text: "Printer disabled.Try save transaction without printer.")
            self.trySaveTransaction()
        }
    }
    
    func tryPrintFinancialVoucher(){
        settings.printer?.printShoppingCartVoucherGift(State.shoppingCart, completionHandler: {result in
            if(result == true){
                Util.writeLogCustom(eventName: "print_ticket", name: "Receipts", text: "Receipt printed : \(State.receiptFiscalNumber).Try save transaction.")
                self.promoCart.receiptFiscalNumber = State.receiptFiscalNumber
                self.promoCart.zReportNumber = State.zReportNumber
                self.promoCart.fiscalPrinterSN = State.fiscalPrinterSN
                self.trySaveTransaction()
            }
            else if(result == false){
                Util.writeLogCustom(eventName: "print_ticket", name: "Receipts", text: "Error print.Receipt not printed!")
                Util.AlertRetryAction(viewController: self, title: Util.getString("Something went wrong"), message: Util.getString("Receipt not printed!"), actionOnRetry: self.tryPrintFinancialVoucher, actionOnCancel: nil)
            }
            else if(result == nil){
                Util.writeLogCustom(eventName: "print_ticket", name: "Receipts", text: "Error print.No network connection!")
                Util.AlertRetryAction(viewController: self, title: Util.getString("Something went wrong"), message: Util.getString("Receipt not printed!"), actionOnRetry: self.tryPrintFinancialVoucher, actionOnCancel: nil)
            }
        })
        if(settings.printer == nil){
            Util.writeLogCustom(eventName: "print_ticket", name: "Receipts", text: "Printer disabled.Try save transaction without printer.")
            self.trySaveTransaction()
        }
    }
    
    func tryPrintRefund(){
        settings.printer?.printShoppingCartRefund(State.shoppingCart,completionHandler: {result in
            if(result == true){
                Util.writeLogCustom(eventName: "print_ticket", name: "Refunds", text: "Refund printed : \(State.receiptFiscalNumber).Try save transaction.")
                self.promoCart.receiptFiscalNumber = State.receiptFiscalNumber
                self.promoCart.zReportNumber = State.zReportNumber
                self.promoCart.fiscalPrinterSN = State.fiscalPrinterSN
                self.trySaveTransaction()
            }
            else if(result == false){
                Util.writeLogCustom(eventName: "print_ticket", name: "Refunds", text: "Error print.Refund not printed!")
                Util.AlertRetryAction(viewController: self, title: Util.getString("Something went wrong"), message: Util.getString("Receipt not printed!"), actionOnRetry: self.tryPrintRefund, actionOnCancel: nil)
            }
            else if(result == nil){
                Util.writeLogCustom(eventName: "print_ticket", name: "Refunds", text: "Error print.No network connection!")
                Util.AlertRetryAction(viewController: self, title: Util.getString("Something went wrong"), message: Util.getString("Receipt not printed!"), actionOnRetry: self.tryPrintRefund, actionOnCancel: nil)
            }
        })
        if(settings.printer == nil){
            Util.writeLogCustom(eventName: "print_ticket", name: "Refunds", text: "Printer disabled.Try save transaction without printer.")
            self.trySaveTransaction()
        }
    }
    
    func onFailureEndPayment(){
        for payment in State.shoppingCart.payments{
            if Util.isOnlinePayment(paymentType: payment.paymentType){
                self.electronicPayments.append(payment)
            }
        }
        if self.electronicPayments.count > 0{
            Util.GeneralAlertWithAction(viewController: self, message: Util.getString("ElectronicPaymentsNotRegistred")) {
                self.renewShoppingCart()
                self.returnToShoppingCart()
            }
        }
        else{
            self.renewShoppingCart()
            self.returnToShoppingCart()
        }
    }
    
    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)
        }
    }
    
    func renewShoppingCart(){
        State.shoppingCart = ShoppingCart()
        self.refreshShoppingCartTotals()
        
        self.resetContact()
        self.resetFidelityCard()
        self.resetLotteryCode()
        
        self.quantity.removeAll()
        
        settings.customerDisplay?.clearCustomerDisplay()
    }
    
    @IBAction func buttonPayment_Click(_ sender: Any) {
        Util.writeLogCustom(eventName: "print_ticket", name: "Receipts", text: "Printer disabled.Try save transaction without printer.")
        settings.printer?.isPrinterStateIdle(completionHandler: { result in
            if result == false{
                return
            }
            else{
                self.afterPrinterOK()
            }
        })
        if settings.printer == nil {
            self.afterPrinterOK()
        }
    }
    
    func afterPrinterOK(){
        if State.shoppingCart.netValue < 0{
            if State.shoppingCart.getTotalDistributedDiscount() != 0{
                Util.GeneralAlertAutoDismiss(viewController: self, message: Util.getString("The purchase amount can not be negative."), time: 1.5)
                return
            }
        }
        
        if State.shoppingCart.isValidForSendingToHI(){
            if State.contactFiscalCodeForTransaction != nil{
                if State.shoppingCart.contact != nil{
                    if !(State.shoppingCart.contact?.IsLegalPerson!)!{
                        self.checkFiscalCode()
                    }
                    else{
                        self.saveTransaction()
                    }
                }
                else{
                    self.checkFiscalCode()
                }
            }
            else if State.shoppingCart.contact == nil{
                self.alertFiscalCodeInvalid(title: Util.getString("Warning"), message: Util.getString("NoContactSelectedForHI"))
            }
            else{
                self.saveTransaction()
            }
        }
        else{
            self.saveTransaction()
        }
    }
    
    func checkFiscalCode(){
        State.validateFiscalCode(fiscalCode: State.contactFiscalCodeForTransaction!, completionHandler: { result in
            if result{
                self.alertSendToHealthInsurance(title: Util.getString("Information"), message: Util.getString("Do you want to send the receipt to Health Insurance?"))
            }
            else{
                self.alertFiscalCodeInvalid(title: Util.getString("Warning"), message: Util.getString("NoFiscalCodeValidForHI"))
            }
        })
    }
    
    func alertFiscalCodeInvalid(title: String, message: String)  {
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let aproveAction = UIAlertAction(title: Util.getString("Continue anyway"), style: .default, handler : { (action) -> Void in
            State.shoppingCart.allowSendToHealthInsurance = nil
            self.saveTransaction()
        })
        
        let cancelAction = UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler : { (action) -> Void in
            return
        })
        
        alertController.addAction(aproveAction)
        alertController.addAction(cancelAction)
        
        self.present(alertController, animated: true, completion: nil)
    }
    
    
    func saveTransaction(){
        if State.isLotteryActive && State.lotteryCode != nil && self.isValidForLottery() == false{
            return
        }
        
        self.shoppingCart = State.shoppingCart
        self.fiscalCode = State.contactFiscalCodeForTransaction
        if settings.FiscalDocumentType == 1{
            if let contact = State.shoppingCart.contact{
                if contact.isValidForInvoicing() {
                    if contact.IsLegalPerson != nil && contact.IsLegalPerson! {
                        if !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()
                            }) {
                                if !State.shoppingCart.isRecalculated {
                                    State.shoppingCart.recalculate(completionHandler: {
                                        self.ticketType = TicketType.Receipt
                                        self.openPaymentType()
                                    })
                                }
                                else{
                                    self.ticketType = TicketType.Receipt
                                    self.openPaymentType()
                                }
                            }
                        }
                        else{
                            if !State.shoppingCart.isRecalculated {
                                State.shoppingCart.recalculate(completionHandler: {
                                    self.ticketType = TicketType.Receipt
                                    self.openPaymentType()
                                })
                            }
                            else{
                                self.ticketType = TicketType.Receipt
                                self.openPaymentType()
                            }
                        }
                    }
                    else{
                        if !State.shoppingCart.isRecalculated {
                            State.shoppingCart.recalculate(completionHandler: {
                                self.ticketType = TicketType.Receipt
                                self.openPaymentType()
                            })
                        }
                        else{
                            self.ticketType = TicketType.Receipt
                            self.openPaymentType()
                        }
                    }
                }
                else{
                    self.AlertContact(title: "iPOS", message: Util.getString("The selected contact is missing info required for invoicing.\nPlease edit it."), flag: "edit")
                }
            }
            else{
                self.AlertContact(title: "iPOS", message: Util.getString("Please select a contact."), flag: "select")
            }
        }
        else{
            if(!State.shoppingCart.isRecalculated){
                State.shoppingCart.recalculate(completionHandler: {
                    self.ticketType = TicketType.Receipt
                    self.openPaymentType()
                })
            }
            else{
                self.ticketType = TicketType.Receipt
                self.openPaymentType()
            }
        }
    }
    
    func alertSendToHealthInsurance(title: String, message: String)  {
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let aproveAction = UIAlertAction(title: Util.getString("Yes"), style: .default, handler : { (action) -> Void in
            State.shoppingCart.allowSendToHealthInsurance = true
            self.saveTransaction()
        })
        
        let cancelAction = UIAlertAction(title: Util.getString("No"), style: .default, handler : { (action) -> Void in
            State.shoppingCart.allowSendToHealthInsurance = false
            self.saveTransaction()
        })
        
        alertController.addAction(aproveAction)
        alertController.addAction(cancelAction)
        
        self.present(alertController, animated: true, completion: nil)
    }
    
    func openPaymentType(){
        var itemsWithPositiveQuantity = false
        var itemsWithNegativeQuantity = false
        for item in State.shoppingCart.cartItems {
            if item.Quantity > 0{
                itemsWithPositiveQuantity = true
            }
            if item.Quantity < 0{
                itemsWithNegativeQuantity = true
            }
        }
        
        if settings.storeSetupSettings.posSalesContactRequired == true && State.shoppingCart.contact == nil {
            Util.AlertOperationNotAllowed(viewController: self, message: Util.getString("ContactRequiredToFinalizeSale"))
            return
        }
        
        if itemsWithPositiveQuantity && itemsWithNegativeQuantity { // Mixed receipt not allowed
            Util.AlertOperationNotAllowed(viewController: self, message: Util.getString("MixedTransactionNotAllowed"))
            return
        }
        
        let firstLine = Util.getString("Total").uppercased()
        let secondLine = "\(settings.userSettings.currencyId) \(Util.DoubleToString(State.shoppingCart.netValue))"
        
        let paymentViewController = self.storyboard?.instantiateViewController(withIdentifier: "paymentViewController") as! PaymentViewController
        paymentViewController.totalValueToPay = State.shoppingCart.netValue.rounded(toPlaces: 2)
        paymentViewController.delegate = self
        paymentViewController.ticketType = self.ticketType
        paymentViewController.receiptType = ReceiptType.ShoppingCart
        
        let newPaymentViewController = self.storyboard?.instantiateViewController(withIdentifier: "newPaymentViewController") as! NewPaymentViewController
        newPaymentViewController.delegate = paymentViewController.self
        newPaymentViewController.payments = paymentViewController.payments
        newPaymentViewController.remainingValueToPay = State.shoppingCart.netValue.rounded(toPlaces: 2)
        newPaymentViewController.ticketType = self.ticketType
        newPaymentViewController.contactId = State.shoppingCart.contact?.ContactId
        
        if State.shoppingCart.netValue.rounded(toPlaces: 2) == 0{
            let paymentType = State.paymentType.first(where: { $0.Code == PaymentTypeString.CASH })!
            let payment = newPaymentViewController.newPaymentTypeSelected(paymentType: paymentType, amount: 0)
            paymentViewController.payments = [payment]
            self.navigationController?.pushViewController(paymentViewController, animated: true)
            Util.writeLogCustom(eventName: "save_payment", name: "Payment", text: "Payment selected: \(String(describing: payment.paymentType.Name)) - \(String(describing: payment.amount))")

            settings.customerDisplay?.showCustomerDisplay(line1: firstLine, line2: secondLine)
        }
        else if State.shoppingCart.netValue.rounded(toPlaces: 2) > 0{
            self.navigationController?.pushViewController(paymentViewController, animated: false)
            self.navigationController?.pushViewController(newPaymentViewController, animated: true)

            settings.customerDisplay?.showCustomerDisplay(line1: firstLine, line2: secondLine)
        }
        else{ //Negative amount
            var allItemsHasNegativeQuantity = true
            for item in State.shoppingCart.cartItems {
                if item.Quantity > 0 {
                    allItemsHasNegativeQuantity = false
                    break
                }
            }
            if allItemsHasNegativeQuantity{
                let msg = Util.getString("CreditNote")
                Util.AlertYesNo(viewController: self, title: "iPOS", message: msg, actionYes: {
                    
                    if settings.storeSetupSettings.clientName.uppercased() != "ATELIERVM"
                        && settings.storeSetupSettings.clientName.uppercased() != "DEFAULT"{
                        Util.GeneralAlertAutoDismiss(viewController: self, message: Util.getString("RefundNotAllowed"), time: 1)
                        return
                    }
                    
                    //If all the products has negative quantity, the transaction is considered as a refund.
                    self.ticketType = TicketType.Refund
                    paymentViewController.ticketType = self.ticketType
                    paymentViewController.receiptType = ReceiptType.ShoppingCart
                    
                    let paymentType = State.paymentType.first(where: { $0.Code == PaymentTypeString.CASH })! // Allow Refunds only in cash.
                    let total = State.shoppingCart.netValue.rounded(toPlaces: 2) * (-1)
                    let payment = newPaymentViewController.newPaymentTypeSelected(paymentType: paymentType, amount: total)
                    paymentViewController.totalValueToPay = total
                    paymentViewController.payments = [payment]
                    self.navigationController?.pushViewController(paymentViewController, animated: true)
                    Util.writeLogCustom(eventName: "save_payment", name: "Payment", text: "Payment selected: \(String(describing: payment.paymentType.Name)) - \(String(describing: payment.amount))")

                    settings.customerDisplay?.showCustomerDisplay(line1: firstLine, line2: secondLine)
                })
                {
                    return
                }
            }
            else{
                Util.AlertOperationNotAllowed(viewController: self, message: Util.getString("NegativeReceipt"))
            }
        }
    }
    
    @IBAction func buttonBarcodeScanner_Click(_ sender: Any) {
        self.isLotteryCodeScanned = false
        self.goToScannerViewController()
    }
    
    func goToScannerViewController(){
        let scannerViewController = self.storyboard?.instantiateViewController(withIdentifier: "scannerViewController") as! ScannerViewController
        scannerViewController.delegate = self
        scannerViewController.isSlideButtonVisible = false
        self.navigationController?.pushViewController(scannerViewController, animated: true)
    }
    
    func loadVoucherGenerators(barcode: String, completionHandler: @escaping(Bool) -> Void){
        let start = barcode.index(barcode.startIndex, offsetBy: 0)
        let end = barcode.index(barcode.startIndex, offsetBy: 3)
        let myRange = start..<end
        let prefix = barcode[myRange]
        State.loadVoucherGenerators(prefix: prefix.description) { result in
            if let _ = result{
                completionHandler(true)
            }
            completionHandler(false)
        }
    }
    
    func loadFidelityCardTypes(barcode: String, completionHandler: @escaping(Bool) -> Void){
        let start = barcode.index(barcode.startIndex, offsetBy: 0)
        let end = barcode.index(barcode.startIndex, offsetBy: 3)
        let myRange = start..<end
        let prefix = barcode[myRange]
        State.loadFidelityCardTypes(prefix: prefix.description) { result in
            if let _ = result{
                completionHandler(true)
            }
            completionHandler(false)
        }
    }
    
    func barcodeFound(barcode: String, captureSession: AVCaptureSession) {
        if self.isLotteryCodeScanned {
            _ = self.navigationController?.popViewController(animated: true)
            self.isLotteryCodeScanned = false
            self.validateLotteryCode(text: barcode)
        }
        else{
            let filter: DecodeFilter = DecodeFilter(self.allowDownloadContactOnProcessFidelity, self.allowProcessFidelityAfterContact, self.allowProcessContactAfterFidelity)
            let request: DecodeBarcodeRequest = DecodeBarcodeRequest(barcode: barcode, filter: filter)
            State.decodeBarcode(decodeBarcodeRequest: request, completionHandler: { decodeBarcodeResult in
                switch decodeBarcodeResult.resultType{
                case .None:
                    self.processNone(decodeBarcodeResult: decodeBarcodeResult, barcode: barcode)
                    break
                case .Contact:
                    print("Contact")
                    self.processContact(decodedContact: decodeBarcodeResult, barcode: barcode)
                    break
                case .FidelityCard:
                    print("FidelityCard")
                    self.processFidelityCard(decodedFidelityCard: decodeBarcodeResult, barcode: barcode)
                    break
                case .Product:
                    print("Product")
                    self.processProduct(decodedProduct: decodeBarcodeResult, barcode: barcode)
                    break
                case .Receipt:
                    print("Receipt not implemented here")
                    self.processNone(decodeBarcodeResult: decodeBarcodeResult, barcode: barcode)
                    break
                case .Voucher:
                    print("Voucher")
                    self.processVoucher(decodedVoucher: decodeBarcodeResult, barcode: barcode)
                    break
                case .WorkOrder:
                    print("WorkOrder not implemented here")
                    self.processNone(decodeBarcodeResult: decodeBarcodeResult, barcode: barcode)
                    break
                case .FiscalCode:
                    print("FiscalCode")
                    self.processContactFiscalCode(decodedContact: decodeBarcodeResult, barcode: barcode)
                    break
                }
            })
        }
    }
    
    private func validateVoucher(voucherInfo: VoucherInfo) -> Bool{
        if voucherInfo.status == VoucherStatus.Active{
            if voucherInfo.generator.voucherType != VoucherType.DSC{
                _ = self.navigationController?.popViewController(animated: true)
                Util.GeneralAlert(viewController: self, message: Util.getString("VoucherNonDISC"))
                return false
            }
            
            if voucherInfo.generator.cumulative == false && State.shoppingCart.effects?.count ?? 0 > 0 {
                _ = self.navigationController?.popViewController(animated: true)
                Util.GeneralAlert(viewController: self, message: Util.getString("VoucherNonCumulativeCannotBeUsed"))
                return false
            }
            
            for voucher in State.shoppingCart.vouchersInfo{
                if voucher.generator.cumulative == false{
                    _ = self.navigationController?.popViewController(animated: true)
                    Util.GeneralAlert(viewController: self, message: Util.getString("VoucherNonCumulativeAlreadyPresent"))
                    return false
                }
            }
            
            for voucher in State.shoppingCart.vouchersInfo{
                if(voucher.voucherCode == voucherInfo.voucherCode){
                    _ = self.navigationController?.popViewController(animated: true)
                    Util.GeneralAlert(viewController: self, message: Util.getString("VoucherAlreadyExists"))
                    return false
                }
            }
            return true
        }
        else{
            _ = self.navigationController?.popViewController(animated: true)
            switch voucherInfo.status{
            case VoucherStatus.Inactive?:
                Util.GeneralAlert(viewController: self, message: String.init(format: Util.getString("VoucherInactive"), voucherInfo.voucherCode))
                return false
            case VoucherStatus.Used?:
                Util.GeneralAlert(viewController: self, message: String.init(format: Util.getString("VoucherUsed"), voucherInfo.voucherCode))
                return false
            case VoucherStatus.ValidityNotStarted?:
                Util.GeneralAlert(viewController: self, message: String.init(format: Util.getString("VoucherValidityNotStarted"), voucherInfo.voucherCode))
                return false
            case VoucherStatus.Expired?:
                Util.GeneralAlert(viewController: self, message: String.init(format: Util.getString("VoucherExpired"), voucherInfo.voucherCode))
                return false
            case VoucherStatus.MaxUseCountExceeded?:
                Util.GeneralAlert(viewController: self, message: String.init(format: Util.getString("VoucherMaxUsed"), voucherInfo.voucherCode))
                return false
            case VoucherStatus.Disabled?:
                Util.GeneralAlert(viewController: self, message: String.init(format: Util.getString("VoucherDisabled"), voucherInfo.generator.voucherGeneratorName))
                return false
            default:
                Util.GeneralAlert(viewController: self, message: Util.getString("Invalid voucher state"))
                return false
            }
        }
    }
    
    private func processNone(decodeBarcodeResult: DecodeBarcodeResult, barcode: String){
        var message = Util.getString("Barcode not found!")
        if let resultMessage = decodeBarcodeResult.resultMessage, resultMessage != "OK"{
            message = resultMessage
        }
        _ = self.navigationController?.popViewController(animated: true)
        Util.GeneralAlert(viewController: self, message: message)
    }
    
    private func processProduct(decodedProduct: DecodeBarcodeResult, barcode: String){
        if let product = decodedProduct.product{
            State.barcodeInfo = product
            if product.hasSerialNumber {
                self.alertAddProductSN(barcodeInfo: product, viewController: self, commingFrom: ScannerViewController.self())
            }
            else if product.IsPriceChangeRequired == true{
                self.alertPriceChangeRequired(barcodeInfo: product, viewController: self, commingFrom: ScannerViewController.self())
            }
            else if let decimalPlaces = product.DecimalPlaces, decimalPlaces > 0 {
                self.alertChangeQuantityRequired(barcodeInfo: product, decimalPlaces: decimalPlaces, commingFrom: ScannerViewController.self())
            }
            else{
                let tempShoppingCart = ShoppingCart()
                tempShoppingCart.addItem(barcodeInfo: product)
                tempShoppingCart.recalculate(completionHandler: {
                    State.shoppingCart.addItem(barcodeInfo: product)
                    State.shoppingCart.recalculate() {
                        _ = self.navigationController?.popViewController(animated: true)
                    }
                })
            }
        }
        else{
            var message = Util.getString("Product not found!")
            if let resultMessage = decodedProduct.resultMessage, resultMessage != "OK"{
                message = resultMessage
            }
            Util.GeneralAlert(viewController: self, message: message)
        }
    }
    
    private func processContactFiscalCode(decodedContact: DecodeBarcodeResult, barcode: String){
        if let fiscalCode = decodedContact.fiscalCode{
            _ = self.navigationController?.popViewController(animated: true)
            self.alertContactNotFound(decodedFiscalCode: fiscalCode, fiscalCode: barcode, title: "iPOS", message: String.init(format: Util.getString("AddNewClientForFiscalCode"), "\(barcode)"))
        }
        else{
            _ = self.navigationController?.popViewController(animated: true)
            var message = Util.getString("Contact not found!")
            if let resultMessage = decodedContact.resultMessage, resultMessage != "OK"{
                message = resultMessage
            }
            Util.GeneralAlert(viewController: self, message: message)
        }
    }
    
    func alertContactNotFound(decodedFiscalCode: DecodeFiscalCodeResponse, fiscalCode:String, title: String, message: String)  {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let aproveAction = UIAlertAction(title: Util.getString("Yes"), style: .default, handler : { (action) -> Void in
            self.addNewContact(decodedFiscalCode: decodedFiscalCode, fiscalCode: fiscalCode)
        })
        
        let cancelAction = UIAlertAction(title: Util.getString("No"), style: .default, handler : { (action) -> Void in
            self.lfSelectedContact.text = fiscalCode
            State.contactFiscalCodeForTransaction = fiscalCode
            return
        })
        
        alertController.addAction(aproveAction)
        alertController.addAction(cancelAction)
        
        self.present(alertController, animated: true, completion: nil)
    }
    
    func addNewContact(decodedFiscalCode: DecodeFiscalCodeResponse, fiscalCode: String) {
        let editViewController = (self.storyboard?.instantiateViewController(withIdentifier: "editViewController") as! EditViewController)
        let contact = Contact()
        
        contact.BirthCity = decodedFiscalCode.birthCity
        contact.BirthDate = decodedFiscalCode.birthDate
        contact.Gender = decodedFiscalCode.gender
        contact.RegionCode = decodedFiscalCode.region
        contact.FiscalCode = fiscalCode
        editViewController.contact = contact
        editViewController.isNew = true
        editViewController.delegate = self
        
        self.navigationController?.pushViewController(editViewController, animated: true)
    }
    
    private func processVoucher(decodedVoucher: DecodeBarcodeResult, barcode: String){
        if let voucherInfo = decodedVoucher.voucher{
            if voucherInfo.generator.voucherType == VoucherType.FIN{
                _ = self.navigationController?.popViewController(animated: true)
                
                if voucherInfo.status == VoucherStatus.Inactive{
                    if  State.shoppingCart.cartItems.count > 0 {
                        let message = Util.getString("SellGiftCardWithProductsNotAllowed")
                        Util.GeneralAlert(viewController: self, message: message)
                        return
                    }
                    
                    self.setAlert(voucherInfo: voucherInfo, barcode: barcode)
                }
                else if voucherInfo.status == VoucherStatus.Active{
                    let message = Util.getString("GiftCardAlreadyActive")
                    Util.GeneralAlert(viewController: self, message: message)
                }
                else{
                    let message = Util.getString("GiftCardNonActivable")
                    Util.GeneralAlert(viewController: self, message: message)
                }
            }
            else if self.validateVoucher(voucherInfo: voucherInfo){
                State.shoppingCart.vouchersInfo.append(voucherInfo)
                
//                State.shoppingCart.recalculate {
//                    self.refreshShoppingCartTotals()
//                    _ = self.navigationController?.popViewController(animated: true)
//                }
                State.shoppingCart.recalculate { [weak self] in
                    guard let self = self else { return }
                    
                    if State.shoppingCart.lastPromoEngineResponse?.resultCode == 1 {
                        Util.GeneralAlert(viewController: self, message: Util.getString("Voucher could not be applied."))
                    } else {
                        self.refreshShoppingCartTotals()
                        _ = self.navigationController?.popViewController(animated: true)
                    }
                }
            }else{
                _ = self.navigationController?.popViewController(animated: true)
                Util.GeneralAlert(viewController: self, message: Util.getString("Invalid voucher!"))
            }
        }else{
            _ = self.navigationController?.popViewController(animated: true)
            var message = Util.getString("Voucher not found!")
            if let resultMessage = decodedVoucher.resultMessage, resultMessage != "OK"{
                message = resultMessage
            }
            Util.GeneralAlert(viewController: self, message: message)
        }
    }
    
    func setAlert(voucherInfo: VoucherInfo, barcode: String){
        self.alert = UIAlertController(title: Util.getString("Gift Card inactive"), message: Util.getString("Do you want to activate it?"), preferredStyle: .alert)
        
        alert.addTextField { (textField) in
            textField.text = barcode
            textField.isEnabled = false
            let text: String = Util.getString("Barcode")
            let placeholder: String = ""
            self.setTextField(textField: textField, text: text, placeholder: placeholder, tag: 1)
        }
        
        alert.addTextField { (textField) in
            textField.text = "0.00"
            textField.becomeFirstResponder()
            let text: String = Util.getString("Amount")
            let placeholder: String = ""
            self.setTextField(textField: textField, text: text, placeholder: placeholder, tag: 2)
        }
        
        alert.addAction(UIAlertAction(title: Util.getString("Activate"), style: .default, handler: { [alert] (_) in
            if let barcode = alert.textFields?[0].text, let amount = alert.textFields?[1].text{
            
                self.financialVoucherToActivate = voucherInfo
                self.financialVoucherToActivate.voucherCode = barcode
                self.financialVoucherToActivate.amount = Double(amount)!
                self.financialVoucherToActivate.voucherAction = .Creation
                
                State.shoppingCart.grossValue = Double(amount)!
                State.shoppingCart.discountValue = 0
                State.shoppingCart.netValue = Double(amount)!

                
                State.LoadPaymentTypes(completionHandler: {result in
                    self.ticketType = TicketType.FinancialVoucher
                    self.openPaymentType()
                })
            }
        }))
        
        alert.addAction(UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler: {(_) in
            self.dismiss(animated: true)
        }))
        
        self.present(alert, animated: true, completion: {
            self.alert.textFields?[1].selectAll(self.alert)
        })
    }
    
    func setTextField(textField: UITextField, text: String, placeholder: String, tag: Int){
        textField.tag = tag
        textField.keyboardType = UIKeyboardType.numbersAndPunctuation
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 22))
        label.textAlignment = NSTextAlignment.right
        label.textColor = UIColor(red: 0.78, green: 0.78, blue: 0.80, alpha: 1.0)
        label.text = text
        textField.rightView = label
        textField.rightViewMode = .always
        textField.placeholder = placeholder
        textField.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged)
    }
    
    @objc func textFieldDidChange(_ textField: UITextField) {
        if textField.tag == 1 && textField.isEnabled{
            self.alert.actions[0].isEnabled = false
            if textField.text == nil || textField.text == ""{
                self.alert.actions[0].isEnabled = false
            }
            else{
                if let textFields = self.alert.textFields{
                    if textFields[1].text != nil && textFields[1].text != ""{
                        self.alert.actions[0].isEnabled = true
                    }
                }
            }
        }
        else if textField.tag == 2{
            self.alert.actions[0].isEnabled = false
            if let text = textField.text{
                if text != "" {
                    let newValue = Util.checkNumberOfDecimalPlaces(string: text, digitCount: 2)
                    textField.text = newValue
                    if let _ = Double(newValue){
                        if let textFields = self.alert.textFields{
                            if textFields[0].isEnabled{
                                if (textFields[0].text != nil && textFields[0].text != ""){
                                    self.alert.actions[0].isEnabled = true
                                }
                            }
                            else{
                                self.alert.actions[0].isEnabled = true
                            }
                        }
                    }else{
                        self.alert.actions[0].isEnabled = false
                    }
                }
            }
        }
    }
    
    private func validateFiscalCode(barcode: String){
        State.validateFiscalCode(fiscalCode: barcode, completionHandler: { result in
            if result{
                State.getContactFilteredByFiscalCode(fiscalCode: barcode, completionHandler: { contact in
                    if let contact = contact {
                        self.selectedContact(contact: contact)
                    }
                    else{
                        State.downloadContactFromCentralDB(fiscalCode: barcode, completionHandler: { result in
                            if let result = result, result == true{
                                State.getContactFilteredByFiscalCode(fiscalCode: barcode, completionHandler: { contact in
                                    if let contact = contact {
                                        self.selectedContact(contact: contact)
                                    }
                                    else{
                                        _ = self.navigationController?.popViewController(animated: true)
                                        Util.AlertSystemError(viewController: self, message: "There was something wrong with downloading the contact from the central server.Please try again later!")
                                    }
                                })
                            }
                            else{
                                _ = self.navigationController?.popViewController(animated: true)
                                self.alertContactNotFound(fiscalCode: barcode, title: "iPOS", message: Util.getString("This new client agrees to save his personal information?"))
                            }
                        })
                    }
                })
            }
            else{
                Util.searchedBarcodeNotFoundAlert(code: barcode, message: Util.getString("Fiscal Code invalid"), viewController: self)
            }
        })
    }
    
    private func getFidelityCardInfo(fidelityCard: FidelityCard){
        let barcode = fidelityCard.cardBarcode
        let getCardInfoRequest: GetCardInfoRequest = GetCardInfoRequest(barcode: barcode)
        
        State.getFidelityCardInfo(getCardInfoRequest: getCardInfoRequest) { result in
            if result == nil{
                Util.GeneralAlert(viewController: self, message: Util.getString("Could not read fidelity card status."))
                self.lfFidelityCard.text = barcode + " / " + Util.getString("Points") + ": 0"
            }
            else if result?.error != nil{
                Util.GeneralAlert(viewController: self, message: (result?.error?.userFriendlyMessage)!)
                self.lfFidelityCard.text = barcode + " / " + Util.getString("Points") + ": 0"
            }
            else{
                self.lfFidelityCard.text = barcode + " / " + Util.getString("Points") + ": \((result?.cardInfo?.availablePointsAmount)!)"
            }
            
            fidelityCard.cardInfo = result?.cardInfo
            self.selectedFidelityCard(fidelityCard: fidelityCard)
        }
    }
    
    private func processContact(decodedContact: DecodeBarcodeResult, barcode: String){
        if let contact = decodedContact.contact{
            self.selectedContact(contact: contact)
            
            if self.firstSelection == .None{
                self.firstSelection = .Contact
            }
        }
        else{
            _ = self.navigationController?.popViewController(animated: true)
            var message = Util.getString("Contact not found!")
            if let resultMessage = decodedContact.resultMessage, resultMessage != "OK"{
                message = resultMessage
            }
            Util.GeneralAlert(viewController: self, message: message)
        }
    }
    
    private func processFidelityCard(decodedFidelityCard: DecodeBarcodeResult, barcode: String){
        if let contact = decodedFidelityCard.contact{
            
            if self.allowProcessContactAfterFidelity {
                self.selectedContact(contact: contact)
            }
            else{
                _ = self.navigationController?.popViewController(animated: true)
                if let fidelityCard = contact.FidelityCard{
                    self.selectedFidelityCard(fidelityCard: fidelityCard)
                }
            }
            
            if self.firstSelection == .None{
                self.firstSelection = .FidelityCard
            }
        }
        else if let fidelityCard = decodedFidelityCard.fidelityCard{
            _ = self.navigationController?.popViewController(animated: true)
            self.selectedFidelityCard(fidelityCard: fidelityCard)
            
            if self.firstSelection == .None{
                self.firstSelection = .FidelityCard
            }
        }
        else{
            _ = self.navigationController?.popViewController(animated: true)
            var message = Util.getString("Could not find fidelity card in database.")
            if let resultMessage = decodedFidelityCard.resultMessage, resultMessage != "OK"{
                message = resultMessage
            }
            Util.GeneralAlert(viewController: self, message: message)
        }
    }
    
    func alertContactNotFound(fiscalCode:String, title: String, message: String)  {
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let aproveAction = UIAlertAction(title: Util.getString("Yes"), style: .default, handler : { (action) -> Void in
            self.addNewContact(fiscalCode: fiscalCode)
        })
        
        let cancelAction = UIAlertAction(title: Util.getString("No"), style: .default, handler : { (action) -> Void in
            self.lfSelectedContact.text = fiscalCode
            State.contactFiscalCodeForTransaction = fiscalCode
            return
        })
        
        alertController.addAction(aproveAction)
        alertController.addAction(cancelAction)
        
        self.present(alertController, animated: true, completion: nil)
    }
    
    func addNewContact(fiscalCode: String) {
        let editViewController = (self.storyboard?.instantiateViewController(withIdentifier: "editViewController") as! EditViewController)
        let contact = Contact()
        State.decodeFiscalCode(fiscalCode: fiscalCode) { decodedFiscalCode in
            contact.BirthCity = decodedFiscalCode?.birthCity
            contact.BirthDate = decodedFiscalCode?.birthDate
            contact.Gender = decodedFiscalCode?.gender
            contact.RegionCode = decodedFiscalCode?.region
            contact.FiscalCode = fiscalCode
            editViewController.contact = contact
            editViewController.isNew = true
            editViewController.delegate = self
            self.navigationController?.pushViewController(editViewController, animated: true)
        }
    }
    
    func contactEdited(contact: Contact) {
        self.editedContact(contact: contact)
    }
    
    @IBAction func buttonBarcodeSearch_Click(_ sender: Any) {
        let searchBarcodeViewController = (self.storyboard?.instantiateViewController(withIdentifier: "searchBarcodeViewController") as! SearchBarcodeViewController)
        searchBarcodeViewController.delegate = self
        self.navigationController?.pushViewController(searchBarcodeViewController, animated: true)
    }
    
    func barcodeFound(barcode: String) {
        let filter: DecodeFilter = DecodeFilter(self.allowDownloadContactOnProcessFidelity, self.allowProcessFidelityAfterContact, self.allowProcessContactAfterFidelity)
        let request: DecodeBarcodeRequest = DecodeBarcodeRequest(barcode: barcode, filter: filter)
        State.decodeBarcode(decodeBarcodeRequest: request, completionHandler: { decodeBarcodeResult in
            switch decodeBarcodeResult.resultType{
            case .None:
                self.processNone(decodeBarcodeResult: decodeBarcodeResult, barcode: barcode)
                break
            case .Contact:
                print("Contact")
                self.processContact(decodedContact: decodeBarcodeResult, barcode: barcode)
                break
            case .FidelityCard:
                print("FidelityCard")
                self.processFidelityCard(decodedFidelityCard: decodeBarcodeResult, barcode: barcode)
                break
            case .Product:
                print("Product")
                self.processProduct(decodedProduct: decodeBarcodeResult, barcode: barcode)
                break
            case .Receipt:
                print("Receipt not implemented here")
                self.processNone(decodeBarcodeResult: decodeBarcodeResult, barcode: barcode)
                break
            case .Voucher:
                print("Voucher")
                self.processVoucher(decodedVoucher: decodeBarcodeResult, barcode: barcode)
                break
            case .WorkOrder:
                print("WorkOrder not implemented here")
                self.processNone(decodeBarcodeResult: decodeBarcodeResult, barcode: barcode)
                break
            case .FiscalCode:
                print("FiscalCode")
                self.processContactFiscalCode(decodedContact: decodeBarcodeResult, barcode: barcode)
                break
            }
        })
    }
    
    @IBAction func buttonAddContactToTransaction_Click(_ sender: Any) {
        if let contact = State.shoppingCart.contact{
            self.goToDetailViewController(contact: contact)
        }
        else{
            self.goToMasterViewController()
        }
    }
    
    func addScrollTapGesture(){
        let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(addContactLongTapped(tapGestureRecognizer:)))
        longPressGesture.minimumPressDuration = 0.5
        longPressGesture.delegate = self
        self.buttonAddContactToTransaction.isUserInteractionEnabled = true
        self.buttonAddContactToTransaction.addGestureRecognizer(longPressGesture)
    }
    
    @objc func addContactLongTapped(tapGestureRecognizer: UITapGestureRecognizer){
        if State.shoppingCart.contact != nil {
            self.alertContactOptions()
        }
        else if State.contactFiscalCodeForTransaction != nil && State.contactFiscalCodeForTransaction != "" {
            self.alertFiscalCodeOptions()
        }
        else if State.shoppingCart.fidelityCard != nil && State.shoppingCart.fidelityCard?.cardBarcode != "" {
            self.alertFidelityCardOptions()
        }
    }
    
    func alertFidelityCardOptions(){
        let alert = UIAlertController(title: "", message: "", preferredStyle: .alert)
        
        let removeFiscalCode = UIAlertAction(title: Util.getString("RemoveFidelityCard"), style: .destructive) { (action) -> Void in
            self.resetContact()
        }
        
        let cancelAction = UIAlertAction(title: Util.getString("Cancel"), style: .default) { (action) -> Void in
            return
        }
        
        alert.addAction(removeFiscalCode)
        alert.addAction(cancelAction)
        
        self.present(alert, animated: true, completion: nil)
    }
    
    func alertFiscalCodeOptions(){
        let alert = UIAlertController(title: "", message: "", preferredStyle: .alert)
        
        let removeFiscalCode = UIAlertAction(title: Util.getString("RemoveFiscalCode"), style: .destructive) { (action) -> Void in
            self.resetContact()
        }
        
        let cancelAction = UIAlertAction(title: Util.getString("Cancel"), style: .default) { (action) -> Void in
            return
        }
        
        alert.addAction(removeFiscalCode)
        alert.addAction(cancelAction)
        
        self.present(alert, animated: true, completion: nil)
    }
    
    func alertContactOptions(){
        let alert = UIAlertController(title: "", message: "", preferredStyle: .alert)
        
        let removeContact = UIAlertAction(title: Util.getString("RemoveContact"), style: .destructive) { (action) -> Void in
            self.resetContact()
        }
        
        let changeContact = UIAlertAction(title: Util.getString("Change contact"), style: .default) { (action) -> Void in
            self.goToMasterViewController()
        }
        
        let cancelAction = UIAlertAction(title: Util.getString("Cancel"), style: .default) { (action) -> Void in
            return
        }
        
        alert.addAction(removeContact)
        alert.addAction(changeContact)
        alert.addAction(cancelAction)
        
        self.present(alert, animated: true, completion: nil)
    }
    
    func editedContact(contact: Contact){
        self.lfSelectedContact.text = contact.getFullName()
        State.shoppingCart.contact = contact
        State.contactFiscalCodeForTransaction = contact.FiscalCode
        _ = self.navigationController?.popViewController(animated: true)
    }
    
    func setLabelForSelectedContact(){
        if (State.shoppingCart.contact?.IsLegalPerson)!{
            self.lfSelectedContact.text = State.shoppingCart.contact?.FirstName
        }
        else{
            self.lfSelectedContact.text = State.shoppingCart.contact?.getFullName()
        }
    }
    
    func selectedFidelityCard(fidelityCard: FidelityCard){
        State.shoppingCart.fidelityCard = fidelityCard
        self.lfFidelityCard.text = fidelityCard.cardBarcode
        if let availablePointsAmount = fidelityCard.cardInfo?.availablePointsAmount{
            self.lfFidelityCard.text?.append(" / " + Util.getString("Points") + ": \((availablePointsAmount))")
        }
    }
    
    func selectedContactDelegate(contact: Contact){
        let filter: DecodeFilter = DecodeFilter(self.allowDownloadContactOnProcessFidelity, self.allowProcessFidelityAfterContact, self.allowProcessContactAfterFidelity)
        let request: DecodeBarcodeRequest = DecodeBarcodeRequest(barcode: contact.ContactId, filter: filter)
        State.decodeBarcode(decodeBarcodeRequest: request, completionHandler: { decodeBarcodeResult in
            switch decodeBarcodeResult.resultType{
            case .Contact:
                print("Contact")
                self.processContact(decodedContact: decodeBarcodeResult, barcode: contact.ContactId)
                break
            default:
                break
            }
        })
    }
    
    func selectedContact(contact: Contact){
        State.shoppingCart.contact = contact
        State.shoppingCart.allowSendToHealthInsurance = nil
        
        if contact.FidelityCard != nil && self.allowProcessFidelityAfterContact{
            State.shoppingCart.fidelityCard = contact.FidelityCard
            if let fidelityCard = State.shoppingCart.fidelityCard{
                if fidelityCard.cardInfo == nil {
                    self.getFidelityCardInfo(fidelityCard: fidelityCard)
                }
                else{
                    self.selectedFidelityCard(fidelityCard: fidelityCard)
                }
            }
        }
        
        self.onDocumentTypeSelection(contact: contact)
    }
    
    func onDocumentTypeSelection(contact: Contact){
        if settings.FiscalDocumentType == 1{
            State.contactFiscalCodeForTransaction = contact.FiscalCode
            self.setLabelForSelectedContact()
            if contact.isValidForInvoicing() {
                if contact.IsLegalPerson != nil && contact.IsLegalPerson! {
                    if !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.goBackViewController()
                        }
                    }
                    else{
                        self.AlertInvoice(title: "iPOS", message: String.init(format: Util.getString("Are you sure that you want to create invoice for contact with vat code : %@?"),"\(contact.VatCode!)"))
                    }
                }
                else {
                    self.AlertInvoice(title: "iPOS", message: String.init(format: Util.getString("Are you sure that you want to create invoice for contact with fiscal code : %@?"),"\(contact.FiscalCode!)"))
                }
            }
            else{
                self.requiredDataAlert(title: "iPOS", message: Util.getString("This contact is missing info required for invoicing!\nDo you want to edit the selected contact?"))
            }
        }
        else{
            self.setLabelForSelectedContact()
            State.contactFiscalCodeForTransaction = contact.FiscalCode
            self.goBackViewController()
        }
    }
    
    func goBackViewController(){
        _ = self.navigationController?.popViewController(animated: true)
    }
    
    func productSelected(barcodeInfo: WSBarcodeInfo, viewController: UIViewController) {
        if self.canAddProductToCart(barcodeInfo: barcodeInfo, viewController: viewController){
            State.shoppingCart.addItem(barcodeInfo: barcodeInfo.clone())
            State.shoppingCart.recalculate() {
                Util.GeneralAlertAutoDismiss(viewController: viewController, message: Util.getString("Product added to the shopping cart."), time: 0.5)
            }
        }
    }
    
    func canAddProductToCart(barcodeInfo: WSBarcodeInfo, viewController: UIViewController) -> Bool{
        if barcodeInfo.IsPosSaleEnabled != true{
            Util.GeneralAlertAutoDismiss(viewController: viewController, message: Util.getString("Article cannot be sold in cash register."), time: 2.0)
            return false
        }
        if barcodeInfo.IsOutOfStockSaleEnabled != true{
            Util.GeneralAlertAutoDismiss(viewController: viewController, message: Util.getString("Article is out of stock.Cannot be sold in cash register."), time: 2.0)
            return false
        }
        return true
    }
    
    func alertAddProductSN(barcodeInfo: WSBarcodeInfo, viewController: UIViewController, commingFrom: UIViewController){
        if commingFrom.isKind(of: ScannerViewController.self){
            Util.simpleAlertWithTextEdit(title: "iPOS", message: Util.getString("InsertSN"), UIViewController: viewController, actionYes: { text in
                self.addNewObjectAsTextCallback(text: text!, barcodeInfo: barcodeInfo, viewController: viewController, commingFrom: commingFrom)
            }) {
                self.goBackViewController()
            }
        }
        else if commingFrom.isKind(of: SearchBarcodeViewController.self)
            || commingFrom.isKind(of: ShoppingCartViewController.self) {
            Util.simpleAlertWithTextEdit(title: "iPOS", message: Util.getString("InsertSN"), UIViewController: viewController, actionYes: { text in
                self.addNewObjectAsTextCallback(text: text!, barcodeInfo: barcodeInfo, viewController: viewController, commingFrom: commingFrom)
            }) {
                return
            }
        }
    }
    
    func addNewObjectAsTextCallback(text: String, barcodeInfo: WSBarcodeInfo, viewController: UIViewController, commingFrom: UIViewController){
        if text == ""{
            self.alertAddProductSN(barcodeInfo: barcodeInfo, viewController: viewController, commingFrom: commingFrom)
        }
        else{
            barcodeInfo.serialNumber = text
            let tempShoppingCart = ShoppingCart()
            tempShoppingCart.addItem(barcodeInfo: barcodeInfo)
            tempShoppingCart.recalculate(completionHandler: {
                State.shoppingCart.addItem(barcodeInfo: barcodeInfo)
                State.shoppingCart.recalculate() {
                    if commingFrom.isKind(of: ShoppingCartViewController.self){
                        self.quantity.removeAll()
                        self.setQuantityArray()
                        self.tableView.reloadData()
                        self.refreshShoppingCartTotals()
                        self.clearAndFocusBarcodeTextField()
                    }
                    else{
                        self.goBackViewController()
                    }
                }
            })
        }
    }

    func addButtonText() -> String {
        return Util.getString("Add to cart")
    }
    
    func isbagButtonVisible() -> Bool {
        return self.isBagButtonEnabled
    }
    
    func isTabBarVisible() -> Bool {
        return true
    }
    
    func productAddedCount() -> Int {
        var quantity: Double = 0
        for cart in State.shoppingCart.cartItems{
            if cart.Quantity != 0 {
                quantity += 1
            }
        }
        return Int(quantity)
    }
    
    func cancelTicket() {
        self.renewShoppingCart()
        self.returnToShoppingCart()
    }
    
    func printFinancialGiftTicket(payments: [Payment], totalValueToPay: Double, remainingValueToPay: Double, totalValuePayed: Double, change: Double) {
        let printFinancialGiftTicketDispatchGroup = DispatchGroup()
        
        var isVoucherCreated: Bool? = nil
        var voucherStatus: VoucherStatus? = nil
        
        printFinancialGiftTicketDispatchGroup.enter()
        State.getNextTransactionNumber {
            print("Get next receipt number finished: \(State.newTransactionNumber)")
            
            if self.financialVoucherToCreate.voucherGeneratorCode.isEmpty == false{
                printFinancialGiftTicketDispatchGroup.enter()
                self.financialVoucherToCreate.transactionNumber = State.newTransactionNumber
                self.financialVoucherToCreate.transactionTime = Date()
                State.webscreateVoucher(createVoucherRequest: self.financialVoucherToCreate) { response in
                    print("Create voucher finished")
                    if let response = response{
                        if let voucherInfo = response.voucherInfo{
                            self.financialVoucherToActivate = voucherInfo
                            self.financialVoucherToActivate.voucherCode = voucherInfo.voucherCode
                            self.financialVoucherToActivate.amount = voucherInfo.amount
                            self.financialVoucherToActivate.voucherAction = .Creation
                            voucherStatus = voucherInfo.status
                            isVoucherCreated = true
                        }
                        else{
                            let message = response.resultMessage + "." + (response.resultErrorDetails ?? "")
                            Util.GeneralAlert(viewController: self, message: message)
                            isVoucherCreated = false
                        }
                    }
                    else{
                        isVoucherCreated = false
                        NetworkController.AlertConnectionError(viewController: self)
                    }
                    
                    printFinancialGiftTicketDispatchGroup.leave()
                }
            }
            printFinancialGiftTicketDispatchGroup.leave()
        }
        
        printFinancialGiftTicketDispatchGroup.notify(queue: .main) {
            print("Finished all requests.")
            
            if isVoucherCreated == false{
                return
            }
            
            State.shoppingCart.payments = payments
            State.shoppingCart.totalPayed = totalValuePayed
            State.shoppingCart.change = change
            
            self.promoCart = self.createPromoCart()
            self.promoCart.transactionSign = 1
            self.promoCart.receiptType = "F"
            self.promoCart.restValue = State.shoppingCart.change
            self.promoCart.transactionNumber = State.newTransactionNumber
            self.promoCart.receiptFiscalNumber = State.receiptFiscalNumber
            
            if let fidelity = State.shoppingCart.fidelityCard{
                self.promoCart.fidelityCardId = UUID.init(uuidString: fidelity.contactId)
                
                self.promoCart.paybackCard = PaybackCard()
                self.promoCart.paybackCard?.cardNumber = fidelity.cardBarcode
                self.promoCart.paybackCard?.fidelityCardId = UUID.init(uuidString: fidelity.contactId)
            }
            
            State.shoppingCart.vouchersInfo = [self.financialVoucherToActivate]
            let voucherCode = self.financialVoucherToActivate.voucherCode
            let amount = self.financialVoucherToActivate.amount
            
            var action = "N" //None
            if voucherStatus == nil || voucherStatus == .Inactive{
                action = "A" //Activate
            }
           
            let cartVouchers = CartVouchers(voucherCode: voucherCode, categoryCode: VoucherCategory.GFT, voucherStatus: VoucherStatus.Inactive, amount: amount, action: action)
            
            self.promoCart.vouchers = [cartVouchers]
            //save to receipt payments
            if State.shoppingCart.payments.count > 0 {
                State.shoppingCart.payments[0].VoucherCode = self.financialVoucherToActivate.voucherCode
                State.shoppingCart.payments[0].VoucherGeneratorId = self.financialVoucherToActivate.generator.voucherGeneratorId
            }
            
            self.tryPrintFinancialVoucher()
            
            self.resetVouchers()
        }
    }
    
    func resetVouchers(){
        self.financialVoucherToCreate = CreateVoucherRequest()
        self.financialVoucherToActivate = VoucherInfo()
    }
    
    func printReceiptTicket(payments: [Payment], totalValueToPay: Double, remainingValueToPay: Double, totalValuePayed: Double, change: Double){
        State.getNextTransactionNumber {
            State.shoppingCart.payments = payments
            State.shoppingCart.totalPayed = totalValuePayed
            State.shoppingCart.change = change
            
            self.promoCart = self.createPromoCart()
            self.promoCart.transactionSign = 1
            self.promoCart.restValue = State.shoppingCart.change
            
            if State.isLotteryActive && State.lotteryCode != nil && State.lotteryCode != "" {
                self.promoCart.hasLotteryCode = true
            }
            
            if let fidelity = State.shoppingCart.fidelityCard{
                self.promoCart.fidelityCardId = UUID.init(uuidString: fidelity.contactId)
                
                self.promoCart.paybackCard = PaybackCard()
                self.promoCart.paybackCard?.cardNumber = fidelity.cardBarcode
                self.promoCart.paybackCard?.fidelityCardId = UUID.init(uuidString: fidelity.contactId)
            }
            if State.countryVats == nil{
                State.loadCountryVats(completionHandler: { countryVatsResult in
                    self.beginPayment()
                })
            }
            else{
                self.beginPayment()
            }
        }
    }
    
    func printRefundTicket(payments: [Payment], totalValueToPay: Double, remainingValueToPay: Double, totalValuePayed: Double, change: Double){
        
        let printRefundTicketDispatchGroup = DispatchGroup()
        
        printRefundTicketDispatchGroup.enter()
        State.getNextProgressive(tableName: "StoreCreditNote") { response in
            State.nextCreditNoteNumber = response?.resultCode ?? 1
            print("Get next credit note number finished: \(State.nextCreditNoteNumber)")
            printRefundTicketDispatchGroup.leave()
        }
        
        printRefundTicketDispatchGroup.enter()
        State.getNextTransactionNumber {
            print("Get next receipt number finished: \(State.newTransactionNumber)")
            printRefundTicketDispatchGroup.leave()
        }
    
        printRefundTicketDispatchGroup.notify(queue: .main) {
            print("Finished all requests.")
            
            State.shoppingCart.payments = payments
            State.shoppingCart.totalPayed = totalValuePayed
            State.shoppingCart.change = change

            self.promoCart = self.createPromoCart()
            self.promoCart.transactionSign = -1
            self.promoCart.restValue = State.shoppingCart.change

            if let fidelity = State.shoppingCart.fidelityCard{
                self.promoCart.fidelityCardId = UUID.init(uuidString: fidelity.contactId)

                self.promoCart.paybackCard = PaybackCard()
                self.promoCart.paybackCard?.cardNumber = fidelity.cardBarcode
                self.promoCart.paybackCard?.fidelityCardId = UUID.init(uuidString: fidelity.contactId)
            }

            self.tryPrintRefund()
        }
    }
    
    func printTicket(payments: [Payment], totalValueToPay: Double, remainingValueToPay: Double, totalValuePayed: Double, change: Double) {
        if self.ticketType == TicketType.Receipt{
             self.printReceiptTicket(payments: payments, totalValueToPay: totalValueToPay, remainingValueToPay: remainingValueToPay, totalValuePayed: totalValuePayed, change: change)
        }
        else if self.ticketType == TicketType.Refund{
            self.printRefundTicket(payments: payments, totalValueToPay: totalValueToPay, remainingValueToPay: remainingValueToPay, totalValuePayed: totalValuePayed, change: change)
        }
        else if self.ticketType == TicketType.FinancialVoucher{
            self.printFinancialGiftTicket(payments: payments, totalValueToPay: totalValueToPay, remainingValueToPay: remainingValueToPay, totalValuePayed: totalValuePayed, change: change)
        }
    }
    
    func createPromoCart() -> PromoShoppingCart{
        let promoCart = State.shoppingCart.createPromoShoppingCart()
        
        if let contact = State.shoppingCart.contact{
            promoCart.contactId = UUID.init(uuidString: contact.ContactId)
        }
        else{
            promoCart.contactId = nil
        }
        
        promoCart.clientFiscalCode = State.contactFiscalCodeForTransaction
        promoCart.transactionSign = 1
        
        if let userId = settings.LoggedInUserId{
            promoCart.cashierUserId = UUID.init(uuidString: userId)
        }
        
        promoCart.transactionNumber = State.newTransactionNumber
        promoCart.receiptFiscalNumber = State.receiptFiscalNumber
        promoCart.zReportNumber = State.zReportNumber
        promoCart.fiscalPrinterSN = State.fiscalPrinterSN
        
        if settings.userSettings.countryCode != "ITA"{
            promoCart.transactionTime = Util.DateToLongDateISO(date: Date())
        }
        
        return promoCart
    }
    
    @IBAction func buttonFidelityCard_Clicked(_ sender: Any) {
        if State.shoppingCart.fidelityCard == nil{
            Util.GeneralAlertAutoDismiss(viewController: self, message: Util.getString("No fidelity card"), time: 1.5)
        }
        else{
            let fidelityCardController = (self.storyboard?.instantiateViewController(withIdentifier: "fidelityCardController") as! FidelityCardController)
            fidelityCardController.delegate = self
            fidelityCardController.fidelityCard = State.shoppingCart.fidelityCard
            fidelityCardController.contact = State.shoppingCart.contact
            self.navigationController?.pushViewController(fidelityCardController, animated: true)
        }
    }
    
    @IBAction func btDiscount_Click(_ sender: Any) {
        if State.shoppingCart.vouchersInfo.count > 0 {
            let cartVoucherViewController = self.storyboard?.instantiateViewController(withIdentifier: "cartVoucherViewController") as! CartVoucherViewController
            self.navigationController?.pushViewController(cartVoucherViewController, animated: true)
        }
    }
    
    func fakeTextFieldSimulateEditing(){
        self.view.addSubview(self.fakeTextField)
        self.fakeTextField.inputAssistantItem.trailingBarButtonGroups = []
        self.fakeTextField.inputAssistantItem.leadingBarButtonGroups = []
        let inputView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
        inputView.isHidden = true
        self.fakeTextField.inputView = inputView
        self.fakeTextField.becomeFirstResponder()
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField == self.fakeTextField && string == "\n"{
            self.decodeBarcode(barcode: textField.text ?? "")
            self.clearAndFocusBarcodeTextField()
        }
        
        return true
    }
    
    func decodeBarcode(barcode: String){
        let barcodeRequest: DecodeStylesAndBarcodes.DecodeBarcodeRequest = DecodeStylesAndBarcodes.DecodeBarcodeRequest(barcode: barcode)
        State.decodeBarcode(decodeBarcodeRequest: barcodeRequest) { result in
            if let decodeBarcodeResponse = result{
                if let msg = decodeBarcodeResponse.resultMessage{
                    Util.GeneralAlert(viewController: self, message: msg, title: barcode)
                    return
                }
                if let product = decodeBarcodeResponse.product{
                    State.barcodeInfo = product
                    if product.hasSerialNumber {
                        self.alertAddProductSN(barcodeInfo: product, viewController: self, commingFrom: ShoppingCartViewController.self())
                    }
                    else if product.IsPriceChangeRequired == true{
                        self.alertPriceChangeRequired(barcodeInfo: product, viewController: self, commingFrom: ShoppingCartViewController.self())
                    }
                    else if let decimalPlaces = product.DecimalPlaces, decimalPlaces > 0 {
                        self.alertChangeQuantityRequired(barcodeInfo: product, decimalPlaces: decimalPlaces, commingFrom: ShoppingCartViewController.self())
                    }
                    else{
                        let tempShoppingCart = ShoppingCart()
                        tempShoppingCart.addItem(barcodeInfo: product)
                        tempShoppingCart.recalculate(completionHandler: {
                            State.shoppingCart.addItem(barcodeInfo: product)
                            State.shoppingCart.recalculate() {
                                self.quantity.removeAll()
                                self.setQuantityArray()
                                self.tableView.reloadData()
                                self.refreshShoppingCartTotals()
                                self.clearAndFocusBarcodeTextField()
                            }
                        })
                    }
                }
                else{
                    Util.GeneralAlert(viewController: self, message: Util.getString("Barcode not found!"), title: barcode)
                    self.clearAndFocusBarcodeTextField()
                }
            }
            else{
                NetworkController.AlertConnectionError(viewController: self)
                self.clearAndFocusBarcodeTextField()
            }
        }
    }

    func alertPriceChangeRequired(barcodeInfo: WSBarcodeInfo, viewController: UIViewController, commingFrom: UIViewController){
        self.simpleAlertWithTextEdit(title: barcodeInfo.Name, message: Util.getString("InsertNewPrice"), text: "", UIViewController: viewController, actionOk: { value in
            barcodeInfo.SalePrice = Double(value ?? "0.00") ?? 0
            
            if let decimalPlaces = barcodeInfo.DecimalPlaces, decimalPlaces > 0 {
                self.alertChangeQuantityRequired(barcodeInfo: barcodeInfo, decimalPlaces: decimalPlaces, commingFrom: commingFrom)
            }
            else{
                let tempShoppingCart = ShoppingCart()
                tempShoppingCart.addItem(barcodeInfo: barcodeInfo)
                tempShoppingCart.recalculate(completionHandler: {
                    State.shoppingCart.addItem(barcodeInfo: barcodeInfo)
                    State.shoppingCart.recalculate() {
                        if commingFrom.isKind(of: ShoppingCartViewController.self){
                            self.quantity.removeAll()
                            self.setQuantityArray()
                            self.tableView.reloadData()
                            self.refreshShoppingCartTotals()
                            self.clearAndFocusBarcodeTextField()
                        }
                        else{
                            self.goBackViewController()
                        }
                    }
                })
            }
        }) {
            return
        }
    }
    
    var alertPriceChange = UIAlertController()
    func simpleAlertWithTextEdit(title: String, message:String, text: String?, UIViewController: UIViewController, actionOk: @escaping ((String?) -> ()), actionNo: @escaping (() -> ()))   {
        self.alertPriceChange = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        self.alertPriceChange.addTextField { textField in
            textField.text = text
            textField.addTarget(self, action: #selector(self.textChanged(_:)), for: .editingDidBegin)
            textField.addTarget(self, action: #selector(self.textChanged(_:)), for: .editingChanged)
            textField.keyboardType = .numbersAndPunctuation
        }
        
        self.alertPriceChange.addAction(UIAlertAction(title: Util.getString("Ok"), style: .default, handler: {(_) in
            actionOk(self.alertPriceChange.textFields?[0].text)
        }))
        
        self.alertPriceChange.addAction(UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler: {(_) in
            actionNo()
        }))
        
        UIViewController.present(self.alertPriceChange, animated: true, completion: {
        })
    }
    
    @objc func textChanged(_ textField: UITextField) {
        self.alertPriceChange.actions[0].isEnabled = false
        if let text = textField.text{
            if text.isEmpty == false {
                if  Util.isTextDoubleValue(value: text) {
                    if Double(text) != 0 {
                        self.alertPriceChange.actions[0].isEnabled = true
                    }
                    else{
                        self.alertPriceChange.actions[0].isEnabled = false
                    }
                }
                else{
                    self.alertPriceChange.actions[0].isEnabled = false
                }
            }
            else{
                self.alertPriceChange.actions[0].isEnabled = false
            }
        }
    }
    
    func alertChangeQuantityRequired(barcodeInfo: WSBarcodeInfo, decimalPlaces: Int, commingFrom: UIViewController){
        self.simpleAlertChangeQuantity(title: barcodeInfo.Name, message: Util.getString("InsertNewQuantity"), decimalPlaces: decimalPlaces, actionOk: { value in
            
            if let quantityString = value, let quantity = Double(quantityString) {
                barcodeInfo.quantity = quantity
            }
            else{
                let quantityString = Util.DoubleToStringQuantity(1, decimalPlaces: decimalPlaces)
                let quantity: Double = Double(quantityString) ?? 1
                
                barcodeInfo.quantity = quantity
            }
            
            let tempShoppingCart = ShoppingCart()
            tempShoppingCart.addItem(barcodeInfo: barcodeInfo)
            tempShoppingCart.recalculate(completionHandler: {
                State.shoppingCart.addItem(barcodeInfo: barcodeInfo)
                State.shoppingCart.recalculate() {
                    if commingFrom.isKind(of: ShoppingCartViewController.self){
                        self.quantity.removeAll()
                        self.setQuantityArray()
                        self.tableView.reloadData()
                        self.refreshShoppingCartTotals()
                        self.clearAndFocusBarcodeTextField()
                    }
                    else{
                        self.goBackViewController()
                    }
                }
            })
        }) {
            return
        }
    }
        
    var alertChangeQuantity = UIAlertController()
    func simpleAlertChangeQuantity(title: String, message: String, decimalPlaces: Int, actionOk: @escaping ((String?) -> ()), actionNo: @escaping (() -> ())) {
        self.alertChangeQuantity = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        self.alertChangeQuantity.addTextField { textField in
            textField.text = Util.DoubleToStringQuantity(1, decimalPlaces: decimalPlaces)
            textField.quantityDecimalPlaces = decimalPlaces
            textField.addTarget(self, action: #selector(self.quantityChanged(_:)), for: .editingDidBegin)
            textField.addTarget(self, action: #selector(self.quantityChanged(_:)), for: .editingChanged)
            textField.keyboardType = .numbersAndPunctuation
        }
        
        self.alertChangeQuantity.addAction(UIAlertAction(title: Util.getString("Ok"), style: .default, handler: {(_) in
            actionOk(self.alertChangeQuantity.textFields?[0].text)
        }))
        
        self.alertChangeQuantity.addAction(UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler: {(_) in
            actionNo()
        }))
        
        self.present(self.alertChangeQuantity, animated: true, completion: {
            self.alertChangeQuantity.textFields?[0].selectAll(self.alertChangeQuantity)
        })
    }
    
    @objc func quantityChanged(_ textField: UITextField) {
        self.alertChangeQuantity.actions[0].isEnabled = false
        if let text = textField.text{
            if text.isEmpty == false {
                if Util.isTextDoubleValue(text: text, decimalPlaces: textField.quantityDecimalPlaces) {
                    self.alertChangeQuantity.actions[0].isEnabled = true
                }
                else{
                    self.alertChangeQuantity.actions[0].isEnabled = false
                }
            }
            else{
                self.alertChangeQuantity.actions[0].isEnabled = false
            }
        }
    }
    
    func clearAndFocusBarcodeTextField(){
        self.fakeTextField.text = ""
        self.fakeTextField.becomeFirstResponder()
    }
    
    @IBAction func btAddNewItem_Click(_ sender: Any) {
        if State.shoppingCart.cartItems.count > 0 {
            self.alertAddNewItem(availableGenerators: [])
        }
        else{
            var availableGenerators: [VoucherGenerators] = []
            State.loadVoucherGenerators { response in
                if let generators = response{
                    for generator in generators{
                        if generator.isPOSVisible == true{
                            availableGenerators.append(generator)
                        }
                    }
                }
                self.alertAddNewItem(availableGenerators: availableGenerators)
            }
        }
    }
    
    func alertAddNewItem(availableGenerators: [VoucherGenerators]){
        let message = Util.getString("Add")
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let product = UIAlertAction(title: Util.getString("Product"), style: .default, handler : { (action) -> Void in
            self.addProduct()
        })
        product.setValue(Util.resizeImage(sourceImage: UIImage.init(named: "defaultProduct50.png")!, newWidth: 25, newHeight: 25), forKey: "image")
        alertController.addAction(product)
        
        for generator in availableGenerators{
            let voucher = UIAlertAction(title: generator.name, style: .default, handler : { (action) -> Void in
                self.alertActivateVoucher(generator: generator)
            })
            voucher.setValue(Util.resizeImage(sourceImage: UIImage.init(named: "gift.png")!, newWidth: 25, newHeight: 25), forKey: "image")
            alertController.addAction(voucher)
        }
        
        let cancel = UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler : { (action) -> Void in
            return
        })
                
        alertController.addAction(cancel)
        self.present(alertController, animated: true, completion: nil)
    }
    
    func addProduct(){
        let productViewFamilyUserControl = self.storyboard?.instantiateViewController(withIdentifier: "productViewFamilyUserControl") as! ProductFamilyViewController
        productViewFamilyUserControl.isSlideButtonEnabled = false
        productViewFamilyUserControl.delegate = self
        self.navigationController?.pushViewController(productViewFamilyUserControl, animated: true)
    }
    
    func alertActivateVoucher(generator: VoucherGenerators){
        self.alert = UIAlertController(title: generator.name, message: Util.getString("ActivateVoucher"), preferredStyle: .alert)
        
        alert.addTextField { (textFieldBarcode) in
            var placeholder: String = Util.getString("Autogenerated")
            textFieldBarcode.isEnabled = false
            if generator.codeAssignmentMode == "OP"{
                textFieldBarcode.isEnabled = true
                textFieldBarcode.alpha = 1.0
                placeholder = ""
                textFieldBarcode.becomeFirstResponder()
            }
            else if generator.codeAssignmentMode == "AU"{
                textFieldBarcode.isEnabled = false
                textFieldBarcode.alpha = 0.5
                placeholder = Util.getString("Autogenerated")
            }
            let text: String = Util.getString("Barcode")
            self.setTextField(textField: textFieldBarcode, text: text, placeholder: placeholder, tag: 1)
        }
        
        alert.addTextField { (textFieldAmount) in
            let text: String = Util.getString("Amount")
            let placeholder: String = ""
            if generator.codeAssignmentMode == "AU"{
                textFieldAmount.becomeFirstResponder()
            }
            self.setTextField(textField: textFieldAmount, text: text, placeholder: placeholder, tag: 2)
        }
        
        alert.addAction(UIAlertAction(title: Util.getString("Activate"), style: .default, handler: { [alert] (_) in
            if alert.textFields?[0].isEnabled == true{
                if let barcode = alert.textFields?[0].text, let amount = alert.textFields?[1].text{
                    let voucher: ValidateVoucherRequest = ValidateVoucherRequest()
                    voucher.voucherCode = barcode
                    State.validateVoucher(voucherRequest: voucher) { response in
                        if response.voucherInfo.generator.voucherType == VoucherType.FIN{
                            if response.voucherInfo.status == VoucherStatus.Inactive{
                                self.financialVoucherToActivate = response.voucherInfo
                                self.financialVoucherToActivate.voucherCode = barcode
                                self.financialVoucherToActivate.amount = Double(amount)!
                                self.financialVoucherToActivate.voucherAction = .Creation
                                
                                State.shoppingCart.grossValue = Double(amount)!
                                State.shoppingCart.discountValue = 0
                                State.shoppingCart.netValue = Double(amount)!
                               
                                State.LoadPaymentTypes(completionHandler: {result in
                                    self.ticketType = TicketType.FinancialVoucher
                                    self.openPaymentType()
                                })
                            }
                            else if response.voucherInfo.status == VoucherStatus.Active{
                                let message = Util.getString("GiftCardAlreadyActive")
                                Util.GeneralAlert(viewController: self, message: message)
                            }
                            else{
                                let message = Util.getString("GiftCardNonActivable")
                                Util.GeneralAlert(viewController: self, message: message)
                            }
                        }
                        else{
                            Util.GeneralAlert(viewController: self, message: Util.getString("Invalid voucher!"))
                        }
                    }
                }
            }
            else{
                if let amount = alert.textFields?[1].text{
                    
                    self.financialVoucherToCreate = CreateVoucherRequest()
                    self.financialVoucherToCreate.voucherGeneratorCode = generator.code ?? ""
                    self.financialVoucherToCreate.amount = Double(amount)!
                    
                    State.shoppingCart.grossValue = Double(amount)!
                    State.shoppingCart.discountValue = 0
                    State.shoppingCart.netValue = Double(amount)!
                             
                    State.LoadPaymentTypes(completionHandler: {result in
                       self.ticketType = TicketType.FinancialVoucher
                       self.openPaymentType()
                    })
                }
            }
        }))
        
        alert.actions[0].isEnabled = false
        
        alert.addAction(UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler: {(_) in
            self.dismiss(animated: true)
        }))
        
        self.present(alert, animated: true, completion: {
            
        })
    }
    
    func generateVoucher(){
        
    }
    
    func activateVoucher(){
        
    }
    
    func isValidForLottery() -> Bool{
        let clearCodeMessage = "Cancella il codice della lotteria prima di effettuare la vendita."
        if State.shoppingCart.netValue < 1 {
            Util.AlertOperationNotAllowed(viewController: self, message: "Valore totale scontrino deve essere maggiore di 1 EUR per participare alla lotteria! \(clearCodeMessage)")
            return false
        }
        
        if State.shoppingCart.contact != nil {
            if let isLegalPerson = State.shoppingCart.contact?.IsLegalPerson, isLegalPerson == true{
                Util.AlertOperationNotAllowed(viewController: self, message: "Il contatto associato alla vendita deve essere una persona individuale! \(clearCodeMessage)")
                return false
            }
        }
        
        if State.shoppingCart.allowSendToHealthInsurance == true{
            Util.AlertOperationNotAllowed(viewController: self, message: "Non e possibile partecipare alla lotteria se lo scontrino viene inviato alla sistema Tessera Sanitaria! \(clearCodeMessage)")
            return false
        }
        
        return true
    }
    
    @IBAction func btLotteryCode_Click(_ sender: Any) {
        self.isLotteryCodeScanned = true
        self.goToScannerViewController()
    }
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if textField == self.tfLotteryCode{
            self.showLotteryCodeEditor()
            return false
        }
        return true
    }
    
    func showLotteryCodeEditor(){
        let lotteryCode = State.lotteryCode ?? ""
        self.alertLottery(title: "Codice Lotteria", message: "Inserisci il codice lotteria", text: lotteryCode) { text in
            self.validateLotteryCode(text: text)
        } actionNo: {
            return
        }
    }
    
    var alertLotteryCode = UIAlertController()
    func alertLottery(title: String, message: String, text: String?, actionOk: @escaping ((String?) -> ()), actionNo: @escaping (() -> ()))   {
        self.alertLotteryCode = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        self.alertLotteryCode.addTextField { textField in
            textField.text = text
        }
        
        self.alertLotteryCode.addAction(UIAlertAction(title: Util.getString("Ok"), style: .default, handler: {(_) in
            actionOk(self.alertLotteryCode.textFields?[0].text)
        }))
        
        self.alertLotteryCode.addAction(UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler: {(_) in
            actionNo()
        }))
        
        self.present(self.alertLotteryCode, animated: true, completion: {
        })
    }
    
    func validateLotteryCode(text: String?){
        if let lotteryCode = text?.trimmingCharacters(in: .whitespacesAndNewlines){
            if lotteryCode == ""{
                self.resetLotteryCode()
                return
            }
            if lotteryCode.count != 8 {
                Util.AlertOperationNotAllowed(viewController: self, message: "Codice lotteria deve avere 8 caratteri!")
                return
            }
            
            self.setLotteryCode(lotteryCode: lotteryCode)
        }
        else {
            self.resetLotteryCode()
        }
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.dismissKeyboard()
        return true
    }
    
    func dismissKeyboard(){
        self.view.endEditing(true)
    }
    
    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        if textField == self.tfLotteryCode{
            self.resetLotteryCode()
            return false
        }
        return true
    }
    
    func resetLotteryCode(){
        State.lotteryCode = nil
        self.tfLotteryCode.text = ""
    }
    
    func setLotteryCode(lotteryCode: String){
        State.lotteryCode = lotteryCode.uppercased()
        self.tfLotteryCode.text = lotteryCode.uppercased()
    }
    
    func voucherSelected(voucherCode: String) {
        let filter: DecodeFilter = DecodeFilter(self.allowDownloadContactOnProcessFidelity, self.allowProcessFidelityAfterContact, self.allowProcessContactAfterFidelity)
        let request: DecodeBarcodeRequest = DecodeBarcodeRequest(barcode: voucherCode, filter: filter)
        State.decodeBarcode(decodeBarcodeRequest: request, completionHandler: { decodeBarcodeResult in
            switch decodeBarcodeResult.resultType{
            case .None:
                self.processNone(decodeBarcodeResult: decodeBarcodeResult, barcode: voucherCode)
                break
            case .Contact:
                print("Contact")
                self.processNone(decodeBarcodeResult: decodeBarcodeResult, barcode: voucherCode)
                break
            case .FidelityCard:
                print("FidelityCard")
                self.processNone(decodeBarcodeResult: decodeBarcodeResult, barcode: voucherCode)
                break
            case .Product:
                print("Product")
                self.processNone(decodeBarcodeResult: decodeBarcodeResult, barcode: voucherCode)
                break
            case .Receipt:
                print("Receipt not implemented here")
                self.processNone(decodeBarcodeResult: decodeBarcodeResult, barcode: voucherCode)
                break
            case .Voucher:
                print("Voucher")
                self.processVoucher(decodedVoucher: decodeBarcodeResult, barcode: voucherCode)
                break
            case .WorkOrder:
                print("WorkOrder not implemented here")
                self.processNone(decodeBarcodeResult: decodeBarcodeResult, barcode: voucherCode)
                break
            case .FiscalCode:
                print("FiscalCode")
                self.processNone(decodeBarcodeResult: decodeBarcodeResult, barcode: voucherCode)
                break
            }
        })
    }
}
extension ShoppingCartViewController : SlideMenuControllerDelegate {
    
    func leftWillOpen() {
    }
    
    func leftDidOpen() {
    }
    
    func leftWillClose() {
    }
    
    func leftDidClose() {
    }
    
    func rightWillOpen() {
    }
    
    func rightDidOpen() {
    }
    
    func rightWillClose() {
    }
    
    func rightDidClose() {
    }
}
