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

import UIKit
import AVFoundation
import MessageUI

protocol IProductSelectorListener {
    func productSelected(barcodeInfo: WSBarcodeInfo,viewController: UIViewController)
    func addButtonText() -> String
    func isbagButtonVisible() -> Bool
    func productAddedCount() -> Int
    func isTabBarVisible() -> Bool
}

//other detail Item Custom Cell

class WorkOrderDetailViewContoller: UIViewController, UITableViewDelegate,UITableViewDataSource, UIPopoverPresentationControllerDelegate, DiscoverTableViewControllerDelegate, UITextFieldDelegate, ScannerViewControllerDelegate, IProductSelectorListener, PaymentViewControllerDelegate, WorkOrderSMSViewControllerDelegate, SearchBarcodeViewControllerDelegate, WorkOrderConfiguratorViewControllerDelegate, CartItemEditCustomCellDelegate, PriceChangeDelegate {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var buttonPayment: UIButton!
    @IBOutlet weak var advanceButton: UIButton!
    @IBOutlet weak var deliverButton: UIButton!
    @IBOutlet weak var assembleButton: UIButton!
    @IBOutlet weak var paidValue: UILabel!
    @IBOutlet weak var totalValue: UILabel!
    @IBOutlet weak var lfDiscountValue: UITextField!
    @IBOutlet weak var lfVoucherCode: UITextField!
    
    @IBOutlet weak var topView: UIView!
    @IBOutlet weak var searchButton: UIButton!
    @IBOutlet weak var addButton: UIButton!
    @IBOutlet weak var moreInfoButton: UIButton!
    @IBOutlet weak var btSendSMS: UIButton!
    @IBOutlet weak var keyboardSearchButton: UIButton!
    
    @IBOutlet weak var btLotteryCode: UIButton!
    @IBOutlet weak var tfLotteryCode: UITextField!
    var isLotteryCodeScanned: Bool = false
    
    var woNumber: String!
    var woDate: String!
    var woStatus: String!
    var woContactInfo: String!
    var woAdvRequired: String!
    var woSubtotal: String!
    var woBarcode: String?
    
    var parentDetailId:String?
    var numberOfHeaders = 0
    var selectedOrderDetail : WorkOrderDetail!
    var clinicalStatus: ClinicalStatus?
    var isNew = false
    var isLoadWOEnabled: Bool = true
    var voucherValue: Double = 0
    
    var financialVoucherToCreate: CreateVoucherRequest = CreateVoucherRequest()
    var btnBarBadge : MJBadgeBarButton!
    
    var electronicPayments: [Payment] = []
    var quantity = [Double]()
    
    var indexToShow:Int?
    var indexToHide:Int?
    var index: IndexPath?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.allowsMultipleSelection = true
        self.popoverPresentationController?.delegate = self
        self.allowEditing()
        self.delegateFields()
        self.setVoucherDiscountLayout()
        self.resetLotteryCode()
    }
    
    func delegateFields(){
        self.lfDiscountValue.delegate = self
        self.lfVoucherCode.delegate = self
        self.tfLotteryCode.delegate = self
    }
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if textField == self.lfDiscountValue || textField == self.lfVoucherCode{
            return false
        }
        if textField == self.tfLotteryCode{
            self.showLotteryCodeEditor()
            return false
        }
        return true
    }
    
    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        if textField == self.tfLotteryCode{
            self.resetLotteryCode()
            return false
        }
        if isEditing {
            if textField == self.lfVoucherCode{
                Util.AlertYesNo(viewController: self, title: "iPOS", message: Util.getString("RemoveVoucher"), actionYes: {
                    self.clearVoucher()
                    self.calculateTotals()
                }) {
                    
                }
            }
            if textField == self.tfLotteryCode{
                self.resetLotteryCode()
                return false
            }
        }
        return false
    }
    
    func clearVoucherDiscounts(){
        for var detail in State.workOrder.OrderDetail{
            self.clearOrderDetailDiscountOutsideConfigurator(orderDetail: &detail, discountType: enumDiscountTypes.VC)
        }
    }
    
    func clearVoucher(){
        State.workOrder.VoucherValue = nil
        State.workOrder.VoucherCode = nil
        State.workOrder.voucherInfo = nil
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if self.isLoadWOEnabled{
            self.loadWorkOrderAndDetails()
        }
        else{
            self.isLoadWOEnabled = true
        }
        self.createLeftBackButton()
        self.electronicPayments = []
        self.selectedOrderDetail = nil
        
        self.manageCustomLayout()
        
        self.btLotteryCode.isHidden = true
        self.tfLotteryCode.isHidden = true
        self.tfLotteryCode.text = ""
        self.navigationItem.rightBarButtonItem?.isEnabled = true
        
        if State.isLotteryActive{
            self.setLotteryCodePlaceholder()
            self.btLotteryCode.isHidden = false
            self.tfLotteryCode.isHidden = false
            if let lotteryCode = State.lotteryCode{
                self.tfLotteryCode.text = lotteryCode
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
            super.viewWillDisappear(animated)
            self.deselectRow()
    }
    
    func deselectRow(){
        if let index = self.index{
            self.tableView.deselectRow(at: index, animated: false)
            self.indexToHide = index.row + 1
            self.indexToShow = nil
            self.tableView.beginUpdates()
            self.tableView.endUpdates()
        }
    }
    
    func setQuantityArray(){
        for detail in State.workOrder.OrderDetail{
            self.quantity.append(detail.OrderedQuantity)
        }
    }
    
    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
    }
    
    override func viewDidLayoutSubviews() {
        super.viewWillLayoutSubviews()
        self.view.layoutIfNeeded()
    }
    
    func resizeButtonImages(){
        self.addButton.setImage(Util.resizeImage(sourceImage: UIImage.init(named: "addButton.png")!, newWidth: 30, newHeight: 30), for: .normal)
        self.searchButton.setImage(Util.resizeImage(sourceImage: UIImage.init(named: "barcodeScanner.png")!, newWidth: 30, newHeight: 30), for: .normal)
        self.moreInfoButton.setImage(Util.resizeImage(sourceImage: UIImage.init(named: "Info.png")!, newWidth: 30, newHeight: 30), for: .normal)
        self.keyboardSearchButton.setImage(Util.resizeImage(sourceImage: UIImage.init(named: "keyboard.png")!, newWidth: 30, newHeight: 30), for: .normal)
    }
    
    func loadWorkOrderAndDetails(){
        if self.isNew {
            self.initNewWorkOrder()
            self.setLabelsValues()
            self.setBottomButtonStatus()
            self.tableView.reloadData()
        }
        else{
            if isEditing {
                State.LoadPaymentTypes(completionHandler: {result in })
                self.setLabelsValues()
                self.setBottomButtonStatus()
                self.tableView.reloadData()
            }
            else{
                State.getCurrentWorkOrder { result in
                    if result {
                        State.LoadPaymentTypes(completionHandler: { result in })
                        
                        if State.workOrder.VoucherCode.isNullOrEmpty == false && State.workOrder.isVoucherCumulative == nil{
                            State.getGeneratorByVoucherCode(voucherCode: State.workOrder.VoucherCode!) { result in
                                if let vg = result{
                                    State.workOrder.isVoucherCumulative = vg.cumulative
                                }
                            }
                        }
                        
                        self.initExistingWorkOrder()
                        self.setBottomButtonStatus()
                        self.allowEditing()
                        self.tableView.reloadData()
                    }
                    else{
                        NetworkController.AlertConnectionError(viewController: self)
                        self.disableControls()
                    }
                }
            }
        }
    }
    
    private func getFidelityCardInfo(completionHandler: @escaping () -> Void){
        if let barcode = State.workOrder.contact.FidelityCard?.cardBarcode{
            let getCardInfoRequest: GetCardInfoRequest = GetCardInfoRequest(barcode: barcode)
            
            State.getFidelityCardInfo(getCardInfoRequest: getCardInfoRequest) { result in
                State.workOrder.contact.FidelityCard?.cardInfo = result?.cardInfo
                completionHandler()
            }
        }
        else{
            completionHandler()
        }
    }
    
    private func tryUseVoucher(completionHandler: @escaping (Bool) -> Void){
        if State.workOrder.VoucherCode.isNullOrEmpty == false && State.workOrder.VoucherValue != nil {
            State.tryUseVoucher { result in
                if let result = result{
                    if result.shouldVoucherBeUnlocked && result.isVoucherUnlocked == false{
                        Util.AlertOperationNotAllowed(viewController: self, message: Util.getString("ErrorUnlockVoucher"))
                        completionHandler(false)
                        return
                    }
                    else if result.isVoucherRedeemed == false{
                        Util.AlertOperationNotAllowed(viewController: self, message: Util.getString("ErrorRedeemVoucher"))
                        completionHandler(false)
                        return
                    }
                    else{
                        completionHandler(true)
                        return                        
                    }
                }
                else{
                    NetworkController.AlertConnectionError(viewController: self)
                    completionHandler(false)
                    return
                }
            }
        }
        else{
            completionHandler(true)
            return
        }
    }
    
    func disableControls(){
        self.buttonPayment.isEnabled = false
        self.advanceButton.isEnabled = false
        self.assembleButton.isEnabled = false
        self.deliverButton.isEnabled = false
        self.addButton.isEnabled = false
        self.searchButton.isEnabled = false
        self.keyboardSearchButton.isEnabled = false
        self.btSendSMS.isEnabled = false
        self.navigationItem.rightBarButtonItem = nil
    }
    
    func createLeftBackButton(){
        if isEditing{
            let backButton = UIBarButtonItem(title: Util.getString("Cancel"), style: .done, target: self, action: #selector(self.backButtonPressed))
            self.navigationItem.leftBarButtonItem = backButton
            self.navigationItem.leftItemsSupplementBackButton = false
        }
        else{
            self.navigationItem.leftBarButtonItem = nil
            self.navigationItem.leftItemsSupplementBackButton = true
        }
    }
    
    @objc func backButtonPressed(){
        if isEditing{
            Util.AlertYesNo(viewController: self, title: "iPOS", message: Util.getString("Are you sure you want to cancel? All changes will be lost!"), actionYes: {
                _ = self.navigationController?.popViewController(animated: true)
            }, actionNo: {
                return
            })
        }
        else{
            _ = self.navigationController?.popViewController(animated: true)
        }
    }
    
    func allowEditing(){
        if self.isNew {
            self.navigationItem.rightBarButtonItem = self.editButtonItem
        }
        else{
            if State.workOrder.SaleState < EnumOrderSaleState.Closed.rawValue {
                self.navigationItem.rightBarButtonItem = self.editButtonItem
            }
            else{
                self.navigationItem.rightBarButtonItem = nil
            }
        }
        
        super.setEditing(self.isNew, animated: self.isNew)
        self.tableView.setEditing(self.isNew, animated: self.isNew)
    }
    
    func setBottomButtonStatus(){
        if self.isNew{
            self.deliverButton.isEnabled = false
            self.buttonPayment.isEnabled = false
            self.assembleButton.isEnabled = false
            self.btSendSMS.isEnabled = false
        }
        else{
            self.deliverButton.isEnabled = false
            self.buttonPayment.isEnabled = !tableView.isEditing
            self.assembleButton.isEnabled = false
            self.btSendSMS.isEnabled = false
        }
    }
    
    func initNewWorkOrder(){
        self.setControllerStatus(isEnabled: isEditing)
        State.workOrder.CreateStoreId = State.storeId
        State.workOrder.LastActionIndex = 0
        State.workOrder.SaleState = EnumOrderSaleState.NotConfirmed.rawValue
        self.woNumber = Util.getString("New")
        self.title = Util.getString("New") + " - " + (State.workOrder.contact.LastName) + " " + (State.workOrder.contact.FirstName)
        self.setLabelsValues()
    }
    
    func initExistingWorkOrder(){
        self.setControllerStatus(isEnabled: isEditing)
        self.title = State.workOrder.OrderNumber.description + " - " + (State.workOrder.contact.LastName) + " " + (State.workOrder.contact.FirstName)
        self.woNumber = "WO " + State.workOrder.OrderNumber.description
        State.LoadWorkOrderDetails(workOder: State.workOrder) {
            State.LoadWorkOrderActions(workOder: State.workOrder) {
                self.checkAdvancePayedValue()
            }
            self.numberOfHeaders = State.workOrder.getNumberOfHeaders()
            self.setLabelsValues()
            self.setQuantityArray()
            self.tableView.reloadData()
        }
    }
    
    override func setEditing(_ editing: Bool, animated: Bool) {
        if State.workOrder.SaleState < EnumOrderSaleState.Closed.rawValue {
            super.setEditing(editing, animated: animated)
            self.tableView.setEditing(editing, animated: animated)
        }

        if isEditing == false {
            //Save
            if State.workOrder.NetValueVatIncluded >= State.workOrder.AdvancePayedValue ?? 0{
                self.validateModifyTime { isValid in
                    if isValid == false{
                        Util.AlertOperationNotAllowed(viewController: self, message: Util.getString("OrderChanged"))
                        self.setButtonStatus(isEnabled: false)
                        return
                    }
                    else{
                        if settings.storeSetupSettings.posAllowModifyWorkOrder {
                            State.workOrder.posAllowModifyContact = false
                            State.workOrder.posAllowAddProducts = true
                            State.workOrder.posAllowChangePrices = false
                            State.workOrder.posAllowApplyPromotions = false
                        }
                        
                        State.workOrder.workOrderSale.StoreId = State.storeId
                        State.workOrder.workOrderSale.CashRegister = State.cashRegister
                        State.SaveWorkOrder(workOrder: State.workOrder, completionHandler: { result in
                            if result {
                                self.isNew = false
                                self.loadWorkOrderAndDetails()
                                self.allowEditing()
                            }
                            else{
                                Util.AlertSystemError(viewController: self)
                                self.setButtonStatus(isEnabled: false)
                                return
                            }
                        })
                    }
                }
            }
            else{
                
                alertIfPaidValueIsHigherThenTotal()
                self.loadWorkOrderAndDetails()
                
            }
            deselectRow()
        }
        else{
            //Edit
            self.tableView.allowsSelectionDuringEditing = editing
            self.setControllerStatus(isEnabled: editing)
        }
        self.createLeftBackButton()
        self.setVoucherDiscountLayout()
    }
    
    func setButtonStatus(isEnabled: Bool){
        self.addButton.isEnabled = isEnabled
        self.searchButton.isEnabled = isEnabled
        self.keyboardSearchButton.isEnabled = isEnabled
        
        self.buttonPayment.isEnabled  = isEnabled
        self.advanceButton.isEnabled  = isEnabled
        self.assembleButton.isEnabled  = isEnabled
        self.deliverButton.isEnabled  = isEnabled
        self.btSendSMS.isEnabled = isEnabled
    }
    
    func setControllerStatus(isEnabled: Bool){
        self.addButton.isEnabled = isEnabled
        self.searchButton.isEnabled = isEnabled
        self.keyboardSearchButton.isEnabled = isEnabled
        
        self.buttonPayment.isEnabled  = !isEnabled
        self.advanceButton.isEnabled  = !isEnabled
        self.assembleButton.isEnabled  = !isEnabled
        self.deliverButton.isEnabled  = !isEnabled
        self.btSendSMS.isEnabled = !isEnabled
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func setLabelsValues(){
        self.paidValue.text = Util.getString("Advance") + ": \(Util.DoubleToString(State.workOrder.AdvancePayedValue ?? 0)) \(settings.userSettings.defaultCurrency)"
        self.totalValue.text = Util.getString("Total") + ": \(Util.DoubleToString(State.workOrder.NetValueVatIncluded)) \(settings.userSettings.defaultCurrency)"
        self.lfDiscountValue.text = Util.getString("Discount") + ": \(Util.DoubleToString(State.workOrder.DiscountValue ?? 0)) \(settings.userSettings.defaultCurrency)"
        self.woAdvRequired = Util.getString("Required") + ": \(Util.DoubleToString(State.workOrder.AdvanceRequiredValue ?? 0)) \(settings.userSettings.defaultCurrency)"
        self.woSubtotal = Util.getString("Subtotal") + ": \(Util.DoubleToString(State.workOrder.GrossValueVatIncluded)) \(settings.userSettings.defaultCurrency)"
        self.woDate = Util.DateToShortDateString(date: State.workOrder.CreateTime)
        self.woContactInfo = State.workOrder.contact.getFullNameSexAge()
        self.woStatus = State.workOrder.getSaleStateName()
        self.woBarcode = State.workOrder.Barcode
        self.setVoucherDiscountLayout()
    }
    
    func alertIfPaidValueIsHigherThenTotal(){
        let alertController = UIAlertController(title:Util.getString("InvalidOperation"), message: Util.getString("PaidValueIsHigherMessage"), preferredStyle: .alert)
        let okButton = UIAlertAction(title:"OK", style: .default)
        alertController.addAction(okButton)
        self.present(alertController, animated: true, completion:nil)
        
    }
    
    func setVoucherDiscountLayout(){
        let discountValue = State.workOrder.DiscountValue ?? 0
        if let voucherCode = State.workOrder.VoucherCode, voucherCode.isEmpty == false{
            self.lfVoucherCode.text = Util.getString("VoucherCode") + ": \(voucherCode)"
            self.lfVoucherCode.isHidden = false
            
            if self.isEditing{
                if State.workOrder.VoucherCode.isNullOrEmpty == false && State.workOrder.VoucherUnlockCode.isNullOrEmpty == true{
                   self.lfVoucherCode.clearButtonMode = .always
                }
                else{
                   self.lfVoucherCode.clearButtonMode = .never
                }
            }
            else{
                self.lfVoucherCode.clearButtonMode = .never
            }
        }
        else{
            self.lfVoucherCode.text = Util.getString("Discount") + ": \(Util.DoubleToString(discountValue)) \(settings.userSettings.defaultCurrency)"
            self.lfVoucherCode.clearButtonMode = .never
            self.lfVoucherCode.isHidden = true
        }
    }
    
    private func validateModifyTime(completionHandler: @escaping(Bool) -> Void){
        if self.isNew{
            completionHandler(true)
            return
        }
        
        var isValid = true
        State.getOrderModifyTime { result in
            if let modifyTime = result{
                if modifyTime != State.workOrder.ModifyTime{
                    isValid = false
                }
            }
            else{
                isValid = false
            }
            completionHandler(isValid)
        }
    }
    
    @IBAction func advanceButton_Click(_ sender: Any) {
        self.validateModifyTime { isValid in
            if isValid == false{
                Util.AlertOperationNotAllowed(viewController: self, message: Util.getString("OrderChanged"))
            }
            else{
                let payAdvenceViewController = (self.storyboard?.instantiateViewController(withIdentifier: "PayAdvenceViewController") as! PayAdvenceViewController)
                self.navigationController?.pushViewController(payAdvenceViewController, animated: true)
            }
        }
    }
    
    @IBAction func assembleButton_Click(_ sender: Any) {
        self.validateModifyTime { isValid in
            if isValid == false{
                Util.AlertOperationNotAllowed(viewController: self, message: Util.getString("OrderChanged"))
            }
            else{
                if settings.storeSetupSettings.clientName.uppercased() == "NAU!"{
                    for orderDetailChild in State.workOrder.getChildCollection(parentId: self.parentDetailId!){  //orderDetail.OrderDetailId
                        if (orderDetailChild.RowType == "LNR" || orderDetailChild.RowType == "LNL")
                                && orderDetailChild.SaleState != EnumDetailSaleState.Arrived.rawValue
                                && orderDetailChild.SaleState != EnumDetailSaleState.Reserved.rawValue
                        {
                            Util.AlertOperationNotAllowed(viewController: self, message: Util.getString("WorkOrderDetailDeliveryValidationMessage"))
                            return
                        }
                    }
                }
                
                let prepare = (self.storyboard?.instantiateViewController(withIdentifier: "prepareViewController") as! PrepareViewController)
                prepare.workOrder = State.workOrder
                prepare.parentDetailId = self.parentDetailId
                self.navigationController?.pushViewController(prepare, animated: true)
            }
        }
    }
    
    @IBAction func deliverButton_Click(_ sender: Any) {
        if !State.workOrder.VoucherCode.isNullOrEmpty && isDeliverPartial(){
            Util.GeneralAlert(viewController: self, message: Util.getString("WorkOrderDetailViewControllerDeliverButtonMessage"))
            return
        }
        
        self.validateModifyTime { isValid in
            if isValid == false{
                Util.AlertOperationNotAllowed(viewController: self, message: Util.getString("OrderChanged"))
            }
            else{
                settings.printer?.isPrinterStateIdle(completionHandler: { result in
                    if result == false{
                        return
                    }
                    else{
                        self.afterPrinterOK()
                    }
                })
                if settings.printer == nil {
                    self.afterPrinterOK()
                }
            }
        }
    }
    
    func afterPrinterOK(){
        if State.workOrder.OrderDetail.count > 0{
            if let orderDetailGlasses = State.workOrder.OrderDetail[0].orderDetailGlasses{
                if orderDetailGlasses.FilterCategory == nil || orderDetailGlasses.FilterCategory == ""{
                    Util.AlertOperationNotAllowed(viewController: self, message: Util.getString("FilterCategoryIsMandatory"))
                    return
                }
            }
        }
        
        if State.workOrder.isValidForSendingToHI(orderDetail: self.selectedOrderDetail){
            State.validateFiscalCode(fiscalCode: State.workOrder.contact.FiscalCode!, 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("Fiscal code is invalid.\nThe receipt will not be sent to Health Insurance"))
                }
            })
        }
        else{
            self.openPaymentType()
        }
    }
    
    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
            self.openPaymentType()
        })
        
        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 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.workOrder.AllowSendToHealthInsurance = true
            self.openPaymentType()
        })
        
        let cancelAction = UIAlertAction(title: Util.getString("No"), style: .default, handler : { (action) -> Void in
            State.workOrder.AllowSendToHealthInsurance = false
            self.openPaymentType()
        })
        
        alertController.addAction(aproveAction)
        alertController.addAction(cancelAction)
        
        self.present(alertController, animated: true, completion: nil)
    }

    func openPaymentType(){
        if State.isLotteryActive && State.lotteryCode != nil && self.isValidForLottery() == false{
            return
        }
        var remainingValueToPay: Double = 0
        var totalValueToPay: Double = 0
        if !isDeliverPartial(){
            remainingValueToPay = State.workOrder.NetValueVatIncluded - State.workOrder.advanceRemainingValue
            totalValueToPay = State.workOrder.NetValueVatIncluded
        }
        else{
            remainingValueToPay = self.selectedOrderDetail.NetRowValueVatIncluded - State.workOrder.advanceRemainingValue
            totalValueToPay = self.selectedOrderDetail.NetRowValueVatIncluded
        }
        //var remainingValueToPay = self.selectedOrderDetail.NetRowValueVatIncluded - State.workOrder.advanceRemainingValue
        
        let paymentViewController = self.storyboard?.instantiateViewController(withIdentifier: "paymentViewController") as! PaymentViewController
        paymentViewController.totalValueToPay = totalValueToPay
        paymentViewController.delegate = self
        paymentViewController.ticketType = TicketType.Receipt
        paymentViewController.receiptType = ReceiptType.WorkOrder
        
        let newPaymentViewController = self.storyboard?.instantiateViewController(withIdentifier: "newPaymentViewController") as! NewPaymentViewController
        newPaymentViewController.delegate = paymentViewController.self
        newPaymentViewController.payments = paymentViewController.payments
        newPaymentViewController.remainingValueToPay = remainingValueToPay
        
        if let advancePayment = self.addAdvancePayment(){
            paymentViewController.payments = [advancePayment]
            if !isDeliverPartial(){
                remainingValueToPay = State.workOrder.NetValueVatIncluded - advancePayment.amount
            }
            else{
                remainingValueToPay = self.selectedOrderDetail.NetRowValueVatIncluded - advancePayment.amount
            }
        }
        if remainingValueToPay == 0{
            self.navigationController?.pushViewController(paymentViewController, animated: true)
        }
        else if remainingValueToPay > 0{
            self.navigationController?.pushViewController(paymentViewController, animated: false)
            self.navigationController?.pushViewController(newPaymentViewController, animated: true)
        }
        else{
            Util.AlertOperationNotAllowed(viewController: self, message: "You can not have the receipt with the negative value")
        }
    }
    
    func cancelTicket() {
        self.endPayment()
    }
    
    func printTicket(payments: [Payment], totalValueToPay: Double, remainingValueToPay: Double, totalValuePayed: Double, change: Double) {
        self.validateModifyTime { isValid in
            if isValid == false{
                Util.AlertOperationNotAllowed(viewController: self, message: Util.getString("OrderChanged"))
            }
            else{
                State.getNextTransactionNumber {
                    State.workOrder.payments = payments
                    State.workOrder.totalPayed = totalValuePayed
                    State.workOrder.change = change
                    
                    State.workOrder.workOrderSale.VoucherValue = self.voucherValue
                    State.workOrder.workOrderSale.payments = payments
                    State.workOrder.workOrderSale.TotalAmount = State.workOrder.NetValueVatIncluded
                    State.workOrder.workOrderSale.RestValue = change
                    State.workOrder.workOrderSale.StoreId = Int(settings.StoreId)!
                    State.workOrder.workOrderSale.CashRegister = Int(settings.CashRegister)!
                    State.workOrder.workOrderSale.ActionType = "RVS"
                    State.workOrder.workOrderSale.ContactId = State.workOrder.contact.ContactId
                    State.workOrder.workOrderSale.TransactionSign = 1
                    State.workOrder.workOrderSale.TransactionNumber = State.newTransactionNumber
                    State.workOrder.workOrderSale.ReceiptFiscalNumber = State.receiptFiscalNumber
                    State.workOrder.workOrderSale.zReportNumber = State.zReportNumber
                    State.workOrder.workOrderSale.fiscalPrinterSN = State.fiscalPrinterSN
                    State.workOrder.workOrderSale.AllowSendToHealthInsurance = State.workOrder.AllowSendToHealthInsurance
                    
                    if settings.userSettings.countryCode != "ITA"{
                        State.workOrder.workOrderSale.transactionTime = Util.DateToLongDateISO(date: Date())
                    }
                    
                    if let fiscalCode = State.workOrder.contact.FiscalCode{
                        State.workOrder.workOrderSale.ContactFiscalCode = fiscalCode
                    }
                    
                    if let userId = settings.LoggedInUserId{
                        State.workOrder.workOrderSale.CashierUserId = userId
                    }
                    
                    State.workOrder.workOrderSale.ParentOrderDetailId = self.selectedOrderDetail.OrderDetailId
                    
                    if State.isLotteryActive && State.lotteryCode != nil && State.lotteryCode != "" {
                        State.workOrder.workOrderSale.hasLotteryCode = true
                    }
                    
                    if let fidelity = State.workOrder.contact.FidelityCard{
                        State.workOrder.workOrderSale.fidelityCardId = UUID.init(uuidString: fidelity.contactId)
                        
                        State.workOrder.workOrderSale.paybackCard = PaybackCard()
                        State.workOrder.workOrderSale.paybackCard?.cardNumber = fidelity.cardBarcode
                        State.workOrder.workOrderSale.paybackCard?.fidelityCardId = UUID.init(uuidString: fidelity.contactId)
                    }
                    
                    self.getFidelityCardInfo(completionHandler: {
                        self.tryUseVoucher { isVoucherUsed in
                            if isVoucherUsed {
                                self.beginPayment()
                            }
                        }
                    })
                }
            }
        }
    }
    
    func addAdvancePayment() -> Payment?{
        if State.workOrder.advanceRemainingValue > 0 {
            let advancePaymentType = self.findAdvancePayments()
            
            let payment = Payment()
            payment.paymentType = advancePaymentType
            payment.paymentTypeId = payment.paymentType.PosPaymentTypeId
            payment.name = payment.paymentType.Name
            
            payment.amount = min(self.selectedOrderDetail.NetRowValueVatIncluded, State.workOrder.advanceRemainingValue).rounded(toPlaces: 2)
            self.voucherValue = payment.amount
            
            return payment
        }
        return nil
    }
    
    func findAdvancePayments() -> PaymentType{
        let advancePaymentType = State.paymentType.first(where: { $0.Code == PaymentTypeString.ADV })!
        
        var paymentTypes: [PaymentType] = []
        
        for oa in State.workOrder.OrderAction{
            if oa.ActionType == "RA1" && oa.ActionState == 1 {
                for rp in oa.receipt?.receiptPayments ?? [] {
                    paymentTypes.append(rp.posPaymentTypes)
                }
            }
        }
        
        var multiplePayments = false
        var lastCategoryCode = ""
        for paymentType in paymentTypes{
            if lastCategoryCode.isEmpty == false && paymentType.CategoryCode != lastCategoryCode{
                multiplePayments = true
            }
            lastCategoryCode = paymentType.CategoryCode ?? ""
        }
        if multiplePayments == false && lastCategoryCode.isEmpty == false{
            advancePaymentType.CategoryCode = lastCategoryCode
        }
        return advancePaymentType
    }
    
    func addCashPaymentPayment(amount: Double) -> Payment{
        let paymentType = State.paymentType.first(where: { $0.Code == PaymentTypeString.CASH })!
        let payment = Payment()
        payment.paymentTypeId = paymentType.PosPaymentTypeId
        payment.name = paymentType.Name
        payment.paymentType = paymentType
        payment.amount = amount
        
        return payment
    }
    
    func getSelectedOrderAndDetails() -> WorkOrder{
        let workOrderPartiallyDeliver = State.workOrder
        workOrderPartiallyDeliver.OrderDetail = State.workOrder.OrderDetail.filter {$0.OrderDetailId == self.selectedOrderDetail.OrderDetailId || $0.ParentOrderDetailId == selectedOrderDetail.OrderDetailId }
        
        return workOrderPartiallyDeliver
    }

    func saveTransaction(){
        let workOrder = self.getSelectedOrderAndDetails()
        workOrder.workOrderSale.receiptLines = State.workOrder.workOrderSale.receiptLines
        State.SaveWorkOrderTransaction(workOrder: workOrder, 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.")
                self.loadWorkOrderAndDetails()
            }
            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)
                self.loadWorkOrderAndDetails()
            }
            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)
                self.loadWorkOrderAndDetails()
            }
            else if(result.resultCode == 0){
                self.endPayment()
                Util.writeLogCustom(eventName: "save_payment", name: "Payment", text: "Transaction succeeded - \(result.transactionId) [\(result.transactionNumber)]")
            }
        })
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return State.workOrder.OrderDetail.count * 2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellHeader = tableView.dequeueReusableCell(withIdentifier: "CellWorkOrderHeaders") as! WorkOrderDetailCustomCell
        let cellDetail = tableView.dequeueReusableCell(withIdentifier: "CellWorkOrderDetails") as! WorkOrderDetailCustomCell
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell2")! as! CartItemEditCustomCell
        
        if(indexPath.row % 2) == 0 || indexPath.row == 0{
            let workOrderDetail = State.workOrder.OrderDetail[indexPath.row/2]
            
            if(workOrderDetail.ParentOrderDetailId == nil){
                cellHeader.backgroundColor = UIColor.lightGray
                cellHeader.wOHcode.text = workOrderDetail.ProductCode
                cellHeader.wOHname.text = workOrderDetail.ProductName
                cellHeader.quantityVar = workOrderDetail.OrderedQuantity
                cellHeader.wOHquantity.text = workOrderDetail.OrderedQuantity.description  + " x "
                cellHeader.wOHprice.text = Util.DoubleToString(workOrderDetail.NetRowValueVatIncluded) + " \(settings.userSettings.defaultCurrency)"
                cellHeader.wOHrowPrice.text = nil
                
                cellHeader.wOHState.image = workOrderDetail.getHeaderRowType()
                cellHeader.wOHStatus.text = workOrderDetail.getSaleStateName()
                
                if(workOrderDetail.isChecked){
                    cellHeader.accessoryType = UITableViewCell.AccessoryType.checkmark
                }
                else {
                    cellHeader.accessoryType = UITableViewCell.AccessoryType.none
                }
                
                let netRowValue = Util.DoubleToStringWithPointSeparator(workOrderDetail.NetRowValueVatIncluded)
                let grossRowValue = Util.DoubleToStringWithPointSeparator(workOrderDetail.GrossUnitValueVatIncluded * workOrderDetail.OrderedQuantity)
                if(workOrderDetail.RowType == rowTypeEnum.other.rawValue){
                    cellHeader.wOHprice.text = Util.DoubleToString(workOrderDetail.GrossUnitValueVatIncluded) + " \(settings.userSettings.defaultCurrency)"
                    if(Double(netRowValue)?.isLess(than: (Double(grossRowValue)!)))!{
                        let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: Util.DoubleToString(workOrderDetail.GrossUnitValueVatIncluded) + " \(settings.userSettings.defaultCurrency)")
                        attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length))
                        cellHeader.wOHprice.attributedText = attributeString
                        cellHeader.wOHrowPrice.text = Util.DoubleToString(workOrderDetail.NetRowValueVatIncluded) + " \(settings.userSettings.defaultCurrency)"
                        cellHeader.wOHrowPrice.textColor = UIColor.red
                        cellHeader.wOHprice.textColor = UIColor.black
                    }
                    else if workOrderDetail.OrderedQuantity > 1{
                        cellHeader.wOHrowPrice.text = Util.DoubleToString(workOrderDetail.NetRowValueVatIncluded) + " \(settings.userSettings.defaultCurrency)"
                    }
                }
                
                return cellHeader
            }
            else {
                cellDetail.isUserInteractionEnabled = false
                cellDetail.wODcode.text = workOrderDetail.ProductCode
                cellDetail.wODname.text = workOrderDetail.ProductName
                cellDetail.wODprice.text = Util.DoubleToString(workOrderDetail.NetRowValueVatIncluded) + " \(settings.userSettings.defaultCurrency)"

                cellDetail.wODState.image = workOrderDetail.getDetailRowType()
                cellDetail.wOOStatus.image = workOrderDetail.getSaleStatusImage()
                
                if(workOrderDetail.isChecked){
                    cellDetail.accessoryType = UITableViewCell.AccessoryType.checkmark
                }
                else {
                    cellDetail.accessoryType = UITableViewCell.AccessoryType.none
                }
                return cellDetail
            }
        }
        else {
            cell.rowNumber = indexPath.row
            cell.delegate = self
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if(self.tableView(tableView, cellForRowAt: indexPath).tag == 0){
            return 64
        }
        else if (self.tableView(tableView, cellForRowAt: indexPath).tag == 2){
            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
                }
            }
            if ((indexPath.row % 2) != 0){
                return 0.0
            }
            
            return 64
        }
        else {
            return 50
        }
    }
    
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let detail = State.workOrder.OrderDetail[indexPath.row / 2]
        
        let deleteRowAction = UITableViewRowAction(style: UITableViewRowAction.Style.destructive, title: Util.getString("Remove"), handler:{action, indexpath in
            self.deleteWorkOrder(detail: detail, row: indexPath.row)
        })
        
        let editRowAction = UITableViewRowAction(style: UITableViewRowAction.Style.default, title: Util.getString("Edit"), handler:{action, indexpath in
            self.editWorkOrder(detail: detail)
        })

        deleteRowAction.backgroundColor = UIColor.red
        editRowAction.backgroundColor = UIColor.blue
        
        if detail.RowType == "GL" || detail.RowType == "CL" {
            if let advancePayed = State.workOrder.AdvancePayedValue, advancePayed > 0 {
                return [editRowAction]
            }
            return [deleteRowAction, editRowAction]
        }
        
        if detail.RowType == "OTH"{
            if let advancePayed = State.workOrder.AdvancePayedValue, advancePayed > 0 {
                return []
            }
        }
        
        return [deleteRowAction]
    }
    
    func editWorkOrder(detail: WorkOrderDetail) {
        State.loadItemTemplates(itemTemplateId: detail.itemTemplateId, filterString: nil) { result in
            if let itemTemplate = result{
                let workOrderConfiguratorViewController = self.storyboard?.instantiateViewController(withIdentifier: "workOrderConfiguratorViewController") as! WorkOrderConfiguratorViewController
                workOrderConfiguratorViewController.configuratorDelegate = self
                workOrderConfiguratorViewController.isNewConfigurator = false
                workOrderConfiguratorViewController.glasses = detail.clone()
                workOrderConfiguratorViewController.itemTemplate = itemTemplate[0]
                
                if let orderDetailGlasses = detail.orderDetailGlasses{
                    workOrderConfiguratorViewController.orderDetailGlasses = orderDetailGlasses.clone()
                }
                
                let technicalDataViewController = self.storyboard?.instantiateViewController(withIdentifier: "technicalDataViewController") as! TechnicalDataViewController
                let technicalDataSecondViewController = self.storyboard?.instantiateViewController(withIdentifier: "technicalDataSecondViewController") as! TechnicalDataSecondViewController
                
                let woGlassesConfiguratorTabBarController = self.storyboard?.instantiateViewController(withIdentifier: "WOGlassesConfiguratorTabBarController") as! WOGlassesConfiguratorTabBarController
                woGlassesConfiguratorTabBarController.workOrderConfiguratorViewController = workOrderConfiguratorViewController
                woGlassesConfiguratorTabBarController.technicalDataViewController = technicalDataViewController
                woGlassesConfiguratorTabBarController.technicalDataSecondViewController = technicalDataSecondViewController
                
                self.navigationController?.pushViewController(woGlassesConfiguratorTabBarController, animated: true)
            }
        }
    }
    
    func deleteWorkOrder(detail: WorkOrderDetail, row: Int){
        detail.OrderedQuantity = 0
        
        State.workOrder.removeItem(at: row / 2)
        self.calculateTotals()
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            let detail = State.workOrder.OrderDetail[indexPath.row]
            detail.OrderedQuantity = 0
            
            State.workOrder.removeItem(at: indexPath.row / 2)
             self.calculateTotals()
        }

    }
    
    //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 {
        // Return false if you do not want the specified item to be editable.
        if isEditing {
            let detail = State.workOrder.OrderDetail[indexPath.row / 2]
            if(detail.SaleState == EnumDetailSaleState.Delivered.rawValue){
                return false
            }
            if detail.ParentOrderDetailId != nil {
                return false
            }
            if (indexPath.row % 2) == 1{
                return false
            }
            return true
        }
        return false
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let workOrderDetail = State.workOrder.OrderDetail[indexPath.row / 2]
        
        self.selectedOrderDetail = workOrderDetail
        let nrOfChilds = workOrderDetail.getNumberOfChild()
        
        if !isEditing{
            for i in (indexPath.row / 2)...(indexPath.row / 2) + nrOfChilds{
                State.workOrder.OrderDetail[i].isChecked = true
                if let cell = tableView.cellForRow(at: IndexPath(row: i*2, section: 0) ) {
                    cell.accessoryType = .checkmark
                }
            }
            self.checkSelectedRow()
        }
        else{
            if nrOfChilds == 0 {
                if let indexPaths = tableView.indexPathsForSelectedRows{
                    for index in indexPaths{
                       if index != indexPath{
                            self.indexToHide = index.row + 1
                            tableView.deselectRow(at: index, animated: false)
                            self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
                            
                        }
                    }
                }
                self.indexToShow = indexPath.row + 1
                self.indexToHide = nil
                self.index = indexPath
                tableView.beginUpdates()
                tableView.endUpdates()
                self.navigationItem.rightBarButtonItem?.isEnabled = true
            }
        }
    }
    
    func isDeliverPartial() -> Bool{
        var isDeliverPartial = true
        var nr = 0
        for detail in State.workOrder.OrderDetail{
            if detail.isChecked == true{
                nr += 1
            }
        }
        if nr == State.workOrder.OrderDetail.count{
            isDeliverPartial = false
        }
            
       return isDeliverPartial
                
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        let workOrderDetail = State.workOrder.OrderDetail[indexPath.row / 2]
        if let selectedIndexPath = tableView.indexPathForSelectedRow{
            self.selectedOrderDetail = State.workOrder.OrderDetail[selectedIndexPath.row / 2]
        }
        else{
            self.selectedOrderDetail = nil
        }
        let nrOfChilds = workOrderDetail.getNumberOfChild()
        if !isEditing{
            for i in (indexPath.row / 2)...(indexPath.row / 2) + nrOfChilds{
                State.workOrder.OrderDetail[i].isChecked = false
                if let cell = tableView.cellForRow(at: IndexPath(row: i*2, section: 0) ) {
                    cell.accessoryType = .none
                }
            }
            self.checkSelectedRow()
        }
        else{
        if nrOfChilds == 0 {
            if tableView.indexPathsForSelectedRows == nil{
                //self.calculateTotals()
                self.indexToHide = indexPath.row + 1
                self.indexToShow = nil
                tableView.beginUpdates()
                tableView.endUpdates()
                self.navigationItem.rightBarButtonItem?.isEnabled = true
            }
            //self.setEditing(false, animated: false)
        }
        }
        
        
    }

    func checkSelectedRow(){
        if State.workOrder.SaleState > EnumOrderSaleState.Ready.rawValue {
            self.deliverButton.isEnabled = false
            self.assembleButton.isEnabled = false
            self.btSendSMS.isEnabled = false
            return
        }
        if let indexPaths = tableView.indexPathsForSelectedRows{
            self.advanceButton.isEnabled = false
            if indexPaths.count == 1{
                self.buttonPayment.isEnabled = true
                let workOrderDetail = State.workOrder.OrderDetail[indexPaths[0].row / 2]
               
                if workOrderDetail.SaleState == EnumDetailSaleState.Preparing.rawValue{
                    self.parentDetailId = workOrderDetail.OrderDetailId
                    
                    if workOrderDetail.getNumberOfChild() == 0{
                        //simple product
                        self.deliverButton.isEnabled = true
                        self.assembleButton.isEnabled = false
                        
                        if ((MFMessageComposeViewController.canSendText() && settings.storeSetupSettings.SMSProvider == "")
                            || ((State.workOrder.contact.Mobile != nil && State.workOrder.contact.Mobile != "") && settings.storeSetupSettings.SMSProvider != "")) {
                            self.btSendSMS.isEnabled = true
                        }
                        else{
                            self.btSendSMS.isEnabled = false
                        }
                        
                        return
                    }
                    else{
                        // glasses
                        self.deliverButton.isEnabled = false
                        self.assembleButton.isEnabled = true
                        self.btSendSMS.isEnabled = false
                        return
                    }
                }
                else if workOrderDetail.SaleState == EnumDetailSaleState.Ready.rawValue{
                    self.parentDetailId = workOrderDetail.OrderDetailId
                    self.deliverButton.isEnabled = true
                    self.assembleButton.isEnabled = false
                    
                    if ((MFMessageComposeViewController.canSendText() && settings.storeSetupSettings.SMSProvider == "")
                        || ((State.workOrder.contact.Mobile != nil && State.workOrder.contact.Mobile != "") && settings.storeSetupSettings.SMSProvider != "")) {
                        self.btSendSMS.isEnabled = true
                    }
                    else{
                        self.btSendSMS.isEnabled = false
                    }
                    
                    return
                }
                else{
                    self.assembleButton.isEnabled = false
                    self.deliverButton.isEnabled = false
                    self.btSendSMS.isEnabled = false
                    return
                }
            }
            else{
                self.deliverButton.isEnabled = true
                self.assembleButton.isEnabled = false
                self.buttonPayment.isEnabled = false
                self.advanceButton.isEnabled = false
                self.btSendSMS.isEnabled = false
                return
            }
        }
        else{
            self.buttonPayment.isEnabled = true
            self.deliverButton.isEnabled = false
            self.assembleButton.isEnabled = false
            self.btSendSMS.isEnabled = false
            self.parentDetailId = nil
            self.checkAdvancePayedValue()
            return
        }
    }
    
    func openProductDetailViewController(styleId: Int){
        State.LoadBarcodeInfo(styleId: styleId, completionHandler: {result in
            if result == nil {
                NetworkController.AlertConnectionError(viewController: self)
            }
            else if result == true{
                if let barcodeInfo = State.barcodeInfo {
                    let tempShoppingCart = ShoppingCart()
                    tempShoppingCart.addItem(barcodeInfo: barcodeInfo)
                    tempShoppingCart.recalculate(completionHandler: {
                        let productDetailViewController = (self.storyboard?.instantiateViewController(withIdentifier: "productDetailViewController") as! ProductDetailViewController)
                        productDetailViewController.cartItem = tempShoppingCart.cartItems[0]
                        productDetailViewController.delegate = self
                        self.navigationController?.pushViewController(productDetailViewController, animated: true)
                    })
                }
                else{
                    NetworkController.AlertConnectionError(viewController: self)
                }
            }
            else {
                Util.GeneralAlert(viewController: self, message: Util.getString("This product does not have a barcode!"))
            }
        })
    }

    
    func displayButtonAction(rowNumber: Int?) {
        if let row = rowNumber{
            if let indexPath = tableView.indexPathForSelectedRow{
                let detail = State.workOrder.OrderDetail[indexPath.row / 2]
                
                if indexPath.row + 1 == row{
                    self.openProductDetailViewController(styleId: detail.StyleId)
                }
            }
        }
    }
    
    func minusButtonAction(rowNumber: Int?) {
        if let row = rowNumber{
            if let indexPath = self.index{
                
                let detail = State.workOrder.OrderDetail[indexPath.row / 2]
                
                if let cell = tableView.cellForRow(at: indexPath) as? WorkOrderDetailCustomCell {
                    if cell.quantityVar > 1{
                        if indexPath.row + 1 == row{
                            cell.quantityVar -= 1
                            cell.wOHquantity.text = cell.quantityVar.description + " x "
                            
                            if detail.canApplyPromotions == false{
                                //extra.DiscountValue! -= extra.DiscountValue! / extra.OrderedQuantity
                            }
                            
                            detail.OrderedQuantity -= 1
                            //isEditing = true
                            
                           // self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
                            
                        }
                    }
                }
                self.calculateTotalsAndReturnToCurrentView()
                //self.calculateTotals()
            }
        }
        //self.setEditing(false, animated: true)
    }
    
    func plusButtonAction(rowNumber: Int?) {
        if let row = rowNumber{
            if let indexPath = self.index{
               
                let detail = State.workOrder.OrderDetail[indexPath.row / 2]
            
                if let cell = tableView.cellForRow(at: indexPath) as? WorkOrderDetailCustomCell {
                    if indexPath.row + 1 == row{
                        cell.quantityVar += 1
                        cell.wOHquantity.text = cell.quantityVar.description + " x "
                        
                        if detail.canApplyPromotions == false{
                            //extra.DiscountValue! += extra.DiscountValue! / extra.OrderedQuantity
                        }
                        
                        detail.OrderedQuantity += 1
                        //isEditing = true
                        //self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
                        
                    }
                }
                //self.calculateTotalsAndReturnToCurrentView()
                self.calculateTotals()
            }
            //saveOrder(workOrder: State.workOrder)
        }
        //self.setEditing(false, animated: true)
        //tableView.setEditing(false, animated: false)
        
    }
    
    
    func saveOrder(workOrder: WorkOrder){
        State.SaveWorkOrder(workOrder: workOrder, completionHandler: { result in
            if result {
                self.isNew = false
                self.loadWorkOrderAndDetails()
            }
            else{
                Util.AlertSystemError(viewController: self)
                //self.setButtonStatus(isEnabled: false)
                return
            }
        })
    }
    
    func discountButtonAction(rowNumber: Int?) {
        if let row = rowNumber{
            if let indexPath = tableView.indexPathForSelectedRow{
                let detail = State.workOrder.OrderDetail[indexPath.row / 2]
                    if indexPath.row + 1 == row{
                        self.changeDiscount(orderDetail: detail)
                    }
                
            }
        }
    }
    
    var changeDiscountForOrderDetail: WorkOrderDetail? = nil
    func changeDiscount(orderDetail: WorkOrderDetail){
        State.loadDiscountCauses(filterString: nil, completionHandler: { result in
            if let discountCauses = result {
                self.changeDiscountForOrderDetail = orderDetail
                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){
        for var detail in State.workOrder.OrderDetail {
            if detail.RowType == rowTypeEnum.other.rawValue && detail.OrderDetailRowNumber == result.rowNumber{
                //detail.importPriceChanges(result: result)
                //detail.addEffect(discountCause: result.discountCause, rowNumber: result.rowNumber, discountValue: result.discountValue, discountPercentage: result.discountPercentage, effectCategory: result.effectCategory)
                self.clearOrderDetailDiscountOutsideConfigurator(orderDetail: &detail, discountType: enumDiscountTypes.MC)
                if result.discountValue > 0 {
                    self.addOrderDetailDiscountOutsideConfigurator(orderDetail: &detail, discountCauseId: result.discountCause.discountCauseId, discountValue: result.discountValue, discountType: enumDiscountTypes.MC, promotionId: nil)
                }
                if self.quantity[result.rowNumber - 1] != detail.OrderedQuantity{
                    self.quantity[result.rowNumber - 1] = detail.OrderedQuantity
                
                }
                self.calculateTotals()
            }
        }
        self.indexToHide = (result.rowNumber - 1) * 2 + 1
        self.indexToShow = nil
        self.tableView.beginUpdates()
        self.tableView.endUpdates()
        self.calculateTotals()
        //self.setEditing(false, animated: true)
        
        
    }
    
    func addOrderDetailDiscount(orderDetail: inout WorkOrderDetail, discountCauseId: Int, discountValue: Double,  discountType: enumDiscountTypes, promotionId: Int?){
        let discount = WorkOrderDetailDiscounts()
        
        discount.OrderDetailId = UUID.init(uuidString: orderDetail.OrderDetailId)!
        discount.DiscountCauseId = discountCauseId
        discount.DiscountType = discountType.rawValue
        discount.DiscountValue = discountValue
        discount.PromotionId = promotionId
        
        if orderDetail.discounts == nil{
            orderDetail.discounts = []
        }
        
        orderDetail.discounts?.append(discount)
        
        if orderDetail.DiscountValue != nil {
            orderDetail.DiscountValue! += discountValue
        }
        else{
            orderDetail.DiscountValue = discountValue
        }
    }
    
    func checkAdvancePayedValue(){
        if State.workOrder.SaleState > EnumOrderSaleState.Ready.rawValue {
            self.advanceButton.isEnabled = false
            return
        }
        
        for detail in State.workOrder.OrderDetail {
            if detail.SaleState < EnumDetailSaleState.Delivered.rawValue {
                self.advanceButton.isEnabled = true
                break
            }
        }
        
        let value = State.workOrder.remainingValueToDeliver - State.workOrder.advanceRemainingValue
        if value > 0 {
            self.advanceButton.isEnabled = true
        }
        else{
            self.advanceButton.isEnabled = false
        }
    }
    
    @IBAction func paymentButton_Click(_ sender: Any) {
        self.alertChooseReportToPrint(viewController: self, message: Util.getString("PrintQuestion"), title: "iPOS")
    }
        
    func alertChooseReportToPrint(viewController: UIViewController, message: String, title: String){
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)

        let report = UIAlertAction(title: Util.getString("Work Order"), style: .default, handler : { (action) -> Void in
            self.printWorkOrder()
        })

        let conformity = UIAlertAction(title: Util.getString("Conformity"), style: .default, handler : { (action) -> Void in
            self.printConformityReport()
        })

        let cancelAction = UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler : { (action) -> Void in
            return
        })
        
        alertController.addAction(report)
        alertController.addAction(conformity)
        alertController.addAction(cancelAction)
        
        viewController.present(alertController, animated: true, completion: nil)
    }

    func printDeliverWorkOrder(){
        settings.printer?.printWorkOrderFiscal(State.workOrder, parentId: self.parentDetailId,  completionHandler: {result in
            if result == true{
                Util.writeLogCustom(eventName: "print_ticket", name: "Deliver_Receipt", text: "Receipt printed : \(State.receiptFiscalNumber).Try save transaction.")
                State.workOrder.workOrderSale.ReceiptFiscalNumber = State.receiptFiscalNumber
                State.workOrder.workOrderSale.zReportNumber = State.zReportNumber
                State.workOrder.workOrderSale.fiscalPrinterSN = State.fiscalPrinterSN
                self.saveTransaction()
            }
            else if(result == false){
                Util.writeLogCustom(eventName: "print_ticket", name: "Deliver_Receipt", text: "Error print.Receipt not printed!")
                Util.AlertRetryAction(viewController: self, title: Util.getString("Something went wrong"), message: Util.getString("Receipt not printed!"), actionOnRetry: self.printDeliverWorkOrder, actionOnCancel: nil)
            }
            else if(result == nil){
                Util.writeLogCustom(eventName: "print_ticket", name: "Deliver_Receipt", text: "Error print.No network connection!")
                Util.AlertRetryAction(viewController: self, title: Util.getString("Something went wrong"), message: Util.getString("Receipt not printed!"), actionOnRetry: self.printDeliverWorkOrder, actionOnCancel: nil)
            }
        })
        if settings.printer == nil {
            Util.writeLogCustom(eventName: "print_ticket", name: "Deliver_Receipt", text: "Printer disabled.Try save transaction without printer.")
            self.saveTransaction()
        }
    }
    
    func onFailureEndPayment(){
        for payment in State.workOrder.workOrderSale.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.endPayment()
            }
        }
        else{
            self.endPayment()
        }
    }

    func printWorkOrder(){
        let workOrderReportRequest = WorkOrderReportRequest()
        workOrderReportRequest.orderId = UUID.init(uuidString: State.workOrder.OrderId)!
        State.getWorkOrderReport(workOrderReportRequest:  workOrderReportRequest) { (result) in
            let documentDetailViewContoller = (self.storyboard?.instantiateViewController(withIdentifier: "documentDetailViewController") as! DocumentDetailViewController)
            documentDetailViewContoller.contact = State.workOrder.contact
            documentDetailViewContoller.binaryData = result.document
            documentDetailViewContoller.viewTitle = "WorkOrderReport.pdf"
            documentDetailViewContoller.title = "WorkOrder Report"
            self.navigationController?.pushViewController(documentDetailViewContoller, animated: true)
        }
    }
    
    func printConformityReport(){
        if self.selectedOrderDetail == nil || self.selectedOrderDetail.ParentOrderDetailId != nil || self.selectedOrderDetail.RowType != "GL"{
            Util.GeneralAlert(viewController: self, message: Util.getString("GlassesNotSelected"))
            return
        }
        
        let conformityReportRequest = ConformityReportRequest()
        conformityReportRequest.storeId = Int(settings.StoreId)!
        conformityReportRequest.orderDetailId = UUID.init(uuidString: self.selectedOrderDetail.OrderDetailId)!
        State.getConformityDataReport(conformityReportRequest: conformityReportRequest) { result in
            let documentDetailViewContoller = (self.storyboard?.instantiateViewController(withIdentifier: "documentDetailViewController") as! DocumentDetailViewController)
            documentDetailViewContoller.contact = State.workOrder.contact
            documentDetailViewContoller.binaryData = result.document
            documentDetailViewContoller.viewTitle = "Conformity.pdf"
            documentDetailViewContoller.title = "Conformity Report"
            self.navigationController?.pushViewController(documentDetailViewContoller, animated: true)
        }
    }
    
    func beginPayment(){
        if State.countryVats == nil{
            State.loadCountryVats(completionHandler: { (countryVatsResult) in
                if let countryVatsResult = countryVatsResult{
                    if countryVatsResult{
                        self.printDeliverWorkOrder()
                    }
                    else{
                        Util.AlertRetryAction(viewController: self, title: Util.getString("Something went wrong"), message: Util.getString("Receipt not printed!"), actionOnRetry: self.beginPayment, actionOnCancel: nil)
                    }
                }
                else{
                    Util.AlertRetryAction(viewController: self, title: Util.getString("Something went wrong"), message: Util.getString("Receipt not printed!"), actionOnRetry: self.beginPayment, actionOnCancel: nil)
                }
            })
        }
        else{
            self.printDeliverWorkOrder()
        }
    }
    
    func endPayment(){
        self.resetLotteryCode()
        self.goToWorkOrderDetailViewController()
    }
    
    func goToWorkOrderDetailViewController(){
        for i in 0..<self.navigationController!.viewControllers.count{
            if (self.navigationController!.viewControllers[i].isKind(of: WorkOrderDetailViewContoller.self)){
                if let viewController = self.navigationController?.viewControllers[i] {
                    _ = self.navigationController?.popToViewController(viewController, animated: false)
                    return
                }
                _ = self.navigationController?.popViewController(animated: true)
                return
            }
        }
    }
    
    @IBAction func searchButton_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 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()
            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.processNone(decodeBarcodeResult: decodeBarcodeResult, barcode: barcode)
                    break
                case .FidelityCard:
                    print("FidelityCard")
                    self.processNone(decodeBarcodeResult: 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.processNone(decodeBarcodeResult: decodeBarcodeResult, barcode: barcode)
                    break
                }
            })
        }
    }
    
    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.workOrder.addItem(barcodeInfo: product)
            self.calculateTotalsAndReturnToCurrentView()
        }
        else{
            var message = Util.getString("Product not found!")
            if let resultMessage = decodedProduct.resultMessage, resultMessage != "OK"{
                message = resultMessage
            }
            Util.GeneralAlert(viewController: self, message: message)
        }
    }
    
    func calculateTotalsAndReturnToCurrentView(){
        self.clearPromoEffects()
        State.workOrder.recalculateOutsideConfigurator {
            self.distributePromoDiscountOnChildren()
            self.calculateOrderTotals()
            self.setVoucherDiscountLayout()
            self.setLabelsValues()
            self.tableView.reloadData()
            self.printTotals()
            
            self.navigationController?.popToViewController(self, animated: true)
        }
    }
    
    func calculateTotals(){
        self.clearPromoEffects()
        State.workOrder.recalculateOutsideConfigurator {
            self.distributePromoDiscountOnChildren()
            self.calculateOrderTotals()
            self.setVoucherDiscountLayout()
            self.setLabelsValues()
            self.tableView.reloadData()
            self.printTotals()
        }
    }
    
    func calculateOrderTotals(){
        State.workOrder.DiscountValue = 0
        State.workOrder.GrossValueVatIncluded = 0
        for var detail in State.workOrder.getHeaderCollection(){
            self.calculateOrderDetailTotal(orderDetail: &detail)
            State.workOrder.GrossValueVatIncluded += detail.GrossUnitValueVatIncluded * detail.OrderedQuantity
            if State.workOrder.DiscountValue != nil{
                State.workOrder.DiscountValue! += (detail.DiscountValue ?? 0)
            }
        }
        State.workOrder.NetValueVatIncluded = State.workOrder.GrossValueVatIncluded - (State.workOrder.DiscountValue ?? 0)
        State.workOrder.TransferTime = nil
    }
    
    func calculateOrderDetailTotal(orderDetail: inout WorkOrderDetail){
        var discountValue: Double = 0
        let childs = State.workOrder.getChildCollection(parentId: orderDetail.OrderDetailId)
        if orderDetail.ParentOrderDetailId == nil && orderDetail.hasPrice == false{
            if childs.count > 0 {
                for child in childs{
                    discountValue = self.calculateOrderDetailDiscount(discountValue: &discountValue, orderDetail: child, quantity: orderDetail.OrderedQuantity)
                }
            }
            else{
                discountValue = self.calculateOrderDetailDiscount(discountValue: &discountValue, orderDetail: orderDetail, quantity: orderDetail.OrderedQuantity)
            }
        }
        else{
            for discount in orderDetail.discounts ?? [] {
                if orderDetail.ParentOrderDetailId != nil &&
                    (discount.DiscountType == enumDiscountTypes.PC.rawValue
                    || discount.DiscountType == enumDiscountTypes.PR.rawValue
                    || discount.DiscountType == enumDiscountTypes.VC.rawValue){
                    
                    discountValue += (discount.DiscountValue ?? 1) / (orderDetail.parentOrderDetail?.OrderedQuantity ?? 1)
                }
                else{
                    discountValue += discount.DiscountValue ?? 0
                }
            }
        }
        
        
        orderDetail.DiscountValue = discountValue
        orderDetail.NetRowValueVatIncluded = orderDetail.OrderedQuantity * orderDetail.GrossUnitValueVatIncluded - discountValue
        if let vatRate = orderDetail.VatRate {
            let netValueVatExcluded = (orderDetail.NetRowValueVatIncluded / (1 + vatRate)).rounded(toPlaces: 2)
            orderDetail.VatValue =  (netValueVatExcluded * vatRate).rounded(toPlaces: 2)
        }
        
        for var child in childs{
            self.calculateOrderDetailTotal(orderDetail: &child)
        }
    }
    
    func calculateOrderDetailDiscount(discountValue: inout Double, orderDetail: WorkOrderDetail, quantity: Double) -> Double{
        for discount in orderDetail.discounts ?? [] {
            if discount.DiscountType == enumDiscountTypes.PC.rawValue
                || discount.DiscountType == enumDiscountTypes.PR.rawValue
                || discount.DiscountType == enumDiscountTypes.VC.rawValue{
                discountValue += discount.DiscountValue ?? 0
            }
            else if orderDetail.RowType == rowTypeEnum.other.rawValue{
                discountValue += (discount.DiscountValue ?? 0)
            }
            else{
                discountValue += (discount.DiscountValue ?? 0) * quantity
            }
        }
        
        return discountValue
    }
    
    func clearPromoEffects(){
        for var orderDetail in State.workOrder.getHeaderCollection(){
            if orderDetail.IsOriginalPriceChanged == true{
                continue
            }
            
            self.clearOrderDetailDiscountOutsideConfigurator(orderDetail: &orderDetail, discountType: .PR)
            self.clearOrderDetailDiscountOutsideConfigurator(orderDetail: &orderDetail, discountType: .VC)
        }
    }
    
    func distributePromoDiscountOnChildren(){
        var firstAppliedPromotion: Int? = nil
        for orderDetail in State.workOrder.OrderDetail{
            if orderDetail.getNumberOfChild() > 0 && orderDetail.ParentOrderDetailId == nil{
                var promoDiscountValue: Double = 0
                if orderDetail.discounts?.count ?? 0 > 0 {
                    for discount in orderDetail.discounts ?? [] {
                        if discount.DiscountType == enumDiscountTypes.PR.rawValue{
                            promoDiscountValue += discount.DiscountValue ?? 0
                            if firstAppliedPromotion == nil{
                                firstAppliedPromotion = discount.PromotionId
                            }
                        }
                    }
                }

                if promoDiscountValue > 0 {
                    self.distributeDiscountOnChildren(glasses: orderDetail, discountValue: promoDiscountValue, discountType: .PR, discountCauseId: -4, promotionId: firstAppliedPromotion)
                }
                
                var voucherDiscountValue: Double = 0
                firstAppliedPromotion = nil
                var voucherDiscountCauseId: Int? = nil
                if orderDetail.discounts?.count ?? 0 > 0 {
                    for discount in orderDetail.discounts ?? [] {
                        if discount.DiscountType == enumDiscountTypes.VC.rawValue {
                            voucherDiscountValue += discount.DiscountValue ?? 0
                            if firstAppliedPromotion == nil{
                                firstAppliedPromotion = discount.PromotionId
                                voucherDiscountCauseId = discount.DiscountCauseId
                            }
                        }
                    }
                }
                
                if voucherDiscountValue > 0 {
                    self.distributeDiscountOnChildren(glasses: orderDetail, discountValue: voucherDiscountValue, discountType: .VC, discountCauseId: voucherDiscountCauseId!, promotionId: firstAppliedPromotion)
                }
            }
        }
    }
    
   
    
    func distributeDiscountOnChildren(glasses: WorkOrderDetail, discountValue: Double, discountType: enumDiscountTypes, discountCauseId: Int, promotionId: Int?){
        var remainingDiscount = discountValue.rounded(toPlaces: 2)
        if remainingDiscount == 0 {
            return
        }
        var childrenSum: Double = 0
        var mostExpensiveChild: WorkOrderDetail? = nil
        for child in State.workOrder.getChildCollection(parentId: glasses.OrderDetailId){
            childrenSum += child.grossRowValueVatIncluded.rounded(toPlaces: 2)

            if mostExpensiveChild == nil {
                mostExpensiveChild = child
            }
            else{
                if child.grossRowValueVatIncluded > mostExpensiveChild!.grossRowValueVatIncluded{
                    mostExpensiveChild = child
                }
            }
        }

        let totalValueToDistributeProportionally = remainingDiscount
        for var child in State.workOrder.getChildCollection(parentId: glasses.OrderDetailId){
            if let mostExpensiveChild = mostExpensiveChild{
                if child.OrderDetailId == mostExpensiveChild.OrderDetailId{
                    continue
                }
            }
            var discount = ((child.grossRowValueVatIncluded / childrenSum) * totalValueToDistributeProportionally).rounded(toPlaces: 2)
            if discount > 0 {
                if discount > child.NetRowValueVatIncluded.rounded(toPlaces: 2){
                    discount = child.NetRowValueVatIncluded.rounded(toPlaces: 2)
                }
                remainingDiscount = remainingDiscount.rounded(toPlaces: 2) - discount.rounded(toPlaces: 2)
                self.addOrderDetailDiscountOutsideConfigurator(orderDetail: &child, discountCauseId: discountCauseId, discountValue: discount, discountType: discountType, promotionId: promotionId)
            }
        }

        if remainingDiscount > 0 && mostExpensiveChild != nil {
            var discountToApply: Double = 0
            if var mostExpensiveChild = mostExpensiveChild{
                if mostExpensiveChild.NetRowValueVatIncluded.rounded(toPlaces: 2) > remainingDiscount.rounded(toPlaces: 2){
                    discountToApply = remainingDiscount.rounded(toPlaces: 2)
                    remainingDiscount = 0
                }
                else{
                    discountToApply = mostExpensiveChild.NetRowValueVatIncluded.rounded(toPlaces: 2)
                    remainingDiscount = remainingDiscount.rounded(toPlaces: 2) - mostExpensiveChild.NetRowValueVatIncluded.rounded(toPlaces: 2)
                }
                self.addOrderDetailDiscountOutsideConfigurator(orderDetail: &mostExpensiveChild, discountCauseId: discountCauseId, discountValue: discountToApply, discountType: discountType, promotionId: promotionId)
            }
        }
    }
    
    func clearOrderDetailDiscount(orderDetail: inout WorkOrderDetail, discountType: enumDiscountTypes){
        if let discounts = orderDetail.discounts{
            for discount in discounts{
                if discount.DiscountType == discountType.rawValue{
                    orderDetail.discounts?.removeAll(where: {$0.OrderDiscountId == discount.OrderDiscountId})
                    if orderDetail.DiscountValue != nil {
                        orderDetail.DiscountValue! -= discount.DiscountValue!
                    }
                }
            }
        }
        
        for var detail in State.workOrder.getChildCollection(parentId: orderDetail.OrderDetailId){
            if detail.applyPromoEngine {
                self.clearOrderDetailDiscount(orderDetail: &detail, discountType: discountType)
            }
        }
    }
    
    private func processVoucher(decodedVoucher: DecodeBarcodeResult, barcode: String){
        if let voucherInfo = decodedVoucher.voucher{
            if voucherInfo.generator.voucherType != VoucherType.DSC{
                Util.GeneralAlert(viewController: self, message: Util.getString("Invalid voucher!"))
            }
            else{
                _ = self.navigationController?.popViewController(animated: true)
                
                if State.workOrder.SaleState == EnumOrderSaleState.Canceled.rawValue
                    || State.workOrder.SaleState == EnumOrderSaleState.Closed.rawValue
                    || State.workOrder.SaleState == EnumOrderSaleState.Ready.rawValue {
                    Util.GeneralAlert(viewController: self, message: Util.getString("VoucherAlreadyConfirmed"))
                }
                else if State.workOrder.VoucherCode != nil && State.workOrder.VoucherCode == ""{
                    Util.GeneralAlert(viewController: self, message: Util.getString("VoucherAlreadyExists"))
                }
                else{
                    if self.validateVoucher(voucherInfo: voucherInfo){
                        State.workOrder.VoucherValue = voucherInfo.amount
                        State.workOrder.VoucherCode = voucherInfo.voucherCode
                        State.workOrder.voucherInfo = voucherInfo // Used by promoengine
                        State.workOrder.isVoucherCumulative = voucherInfo.generator.cumulative
                        self.calculateTotals()
                    }
                }
            }
        }
        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)
        }
    }
    
    private func validateVoucher(voucherInfo: VoucherInfo) -> Bool{
        if voucherInfo.status == VoucherStatus.Active{
            if voucherInfo.generator.voucherType != VoucherType.DSC{
                Util.GeneralAlert(viewController: self, message: Util.getString("VoucherNonDISC"))
                return false
            }
            
            if voucherInfo.generator.cumulative == false {
                for detail in State.workOrder.OrderDetail{
                    if detail.discounts != nil && detail.discounts?.count ?? 0 > 0 {
                        Util.GeneralAlert(viewController: self, message: Util.getString("VoucherNonCumulativeCannotBeUsed"))
                        return false
                    }
                }
            }
            
            if let isVoucherCumulative = State.workOrder.isVoucherCumulative{
                if isVoucherCumulative == false{
                    Util.GeneralAlert(viewController: self, message: Util.getString("VoucherNonCumulativeAlreadyPresent"))
                    return false
                }
            }
            
            if let voucherCode = State.workOrder.VoucherCode{
                if voucherCode == voucherInfo.voucherCode{
                    Util.GeneralAlert(viewController: self, message: Util.getString("VoucherAlreadyExists"))
                    return false
                }
            }
            return true
        }
        else{
            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
            }
        }
    }
    
    func isVoucherValid(voucherInfo: VoucherInfo) -> Bool{
        switch voucherInfo.status{
        case .Active:
            return true
        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
        }
    }
    
    func productSelected(barcodeInfo: WSBarcodeInfo, viewController: UIViewController) {
        if self.canAddProductToCart(barcodeInfo: barcodeInfo, viewController: viewController){
            State.workOrder.addItem(barcodeInfo: barcodeInfo.clone())
            
            self.calculateTotalsAndReturnToCurrentView()
        }
        self.setEditing(true, animated: false)
    }
    
    func canAddProductToCart(barcodeInfo: WSBarcodeInfo, viewController: UIViewController) -> Bool{
        if barcodeInfo.IsWorkOrderSaleEnabled != true{
            Util.GeneralAlertAutoDismiss(viewController: viewController, message: Util.getString("Article cannot be sold in work order."), time: 2.0)
            return false
        }
        return true
    }
    
    func addButtonText() -> String {
        return Util.getString("Add to WO")
    }
    
    func isbagButtonVisible() -> Bool {
        return false
    }
    
    func productAddedCount() -> Int {
        var quantity: Double = 0
        for detail in State.workOrder.OrderDetail{
            if detail.OrderedQuantity != 0 {
                quantity += 1
            }
        }
        return Int(quantity)
    }
    
    func isTabBarVisible() -> Bool {
        return true
    }
    
    @IBAction func moreInfoButton_Click(_ sender: Any) {
        self.viewMoreInfo()
    }
    
    func viewMoreInfo() {
        let infoViewController = (self.storyboard?.instantiateViewController(withIdentifier: "WorkOrderInfoViewController") as! WorkOrderInfoViewController)
        infoViewController.workOrder = State.workOrder
        infoViewController.isNotesEditable = self.isEditing
        self.navigationController?.pushViewController(infoViewController, animated: true)
    }
    
    @IBAction func addButton_Click(_ sender: Any) {
        var alert = UIAlertController()
        if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad ){
            alert = UIAlertController(title: "", message: "", preferredStyle: .alert)
        }
        else{
            alert = UIAlertController(title: "", message: "", preferredStyle: .actionSheet)
        }
        let addNewProductAction = UIAlertAction(title: Util.getString("Product"), style: .default, handler: {(_) in
            self.addNewProduct()
        })
        addNewProductAction.setValue(Util.resizeImage(sourceImage: UIImage.init(named: "defaultProduct50.png")!, newWidth: 25, newHeight: 25), forKey: "image")
        alert.addAction(addNewProductAction)
        
        let addNewGlassesAction = UIAlertAction(title: Util.getString("Glasses"), style: .default, handler: {(_) in
            self.addNewGlasses()
        })
        addNewGlassesAction.setValue(Util.resizeImage(sourceImage: UIImage.init(named: "glasses50.png")!, newWidth: 25, newHeight: 25), forKey: "image")
        if(settings.storeSetupSettings.isOpticalClient == true){
            alert.addAction(addNewGlassesAction)
        }
        
        let addNewContactLensesAction = UIAlertAction(title: Util.getString("Contact Lens"), style: .default, handler: {(_) in
            self.addNewContactLenses()
        })
        addNewContactLensesAction.setValue(Util.resizeImage(sourceImage: UIImage.init(named: "eye50.png")!, newWidth: 25, newHeight: 25), forKey: "image")
        if(settings.storeSetupSettings.isOpticalClient == true){
            //alert.addAction(addNewContactLensesAction)
        }
        
        alert.addAction(UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler: {(_) in
            return
        }))
        
        self.present(alert, animated: true, completion: nil)
    }
    
    func addNewProduct() {
        let productViewFamilyUserControl = self.storyboard?.instantiateViewController(withIdentifier: "productViewFamilyUserControl") as! ProductFamilyViewController
        productViewFamilyUserControl.isSlideButtonEnabled = false
        productViewFamilyUserControl.delegate = self
        self.navigationController?.pushViewController(productViewFamilyUserControl, animated: true)
    }
    
    func addNewGlasses(){
        var orderKitCount = 0
        for detail in State.workOrder.OrderDetail{
            if detail.RowType == rowTypeEnum.glasses.rawValue{
                orderKitCount += 1
            }
        }
        if orderKitCount >= settings.storeSetupSettings.workOrderGlassesMaxCount {
            let message = String.init(format: Util.getString("WorkOrderMaxCountReached"), "\(settings.storeSetupSettings.workOrderGlassesMaxCount)")
            Util.GeneralAlert(viewController: self, message: message)
            return
        }
        
        State.LoadLastClinicalStatus(State.workOrder.contact.ContactId, prescriptionType: "GL") { result in
            if let cs = result {
                self.clinicalStatus = cs
                if self.clinicalStatus != nil && self.clinicalStatus?.PrescriptionType == "GL"{
                    self.selectKIT()
                }
                else{
                    Util.GeneralAlert(viewController: self, message: Util.getString("This contact has no prescription"))
                }
            }else{
                Util.GeneralAlert(viewController: self, message: Util.getString("This contact has no prescription"))
            }
        }
    }
    
    func selectKIT(){
        State.loadItemTemplates(itemTemplateId: nil, filterString: nil) { result in
            if let itemTemplates = result{
                self.openPopUp(itemTemplates, "ItemTemplate", "KIT")
            }
            else{
                NetworkController.AlertConnectionError(viewController: self)
            }
        }
    }
    
    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: ItemTemplate.self){
            let itemTemplate = item as! ItemTemplate
            State.LoadBarcodeInfo(productId: itemTemplate.productId, barcode: nil) { response in
                if response == true {
                    if let barcodeInfo = State.barcodeInfo {
                        let workOrderConfiguratorViewController = self.storyboard?.instantiateViewController(withIdentifier: "workOrderConfiguratorViewController") as! WorkOrderConfiguratorViewController
                        workOrderConfiguratorViewController.barcodeInfo = barcodeInfo
                        workOrderConfiguratorViewController.itemTemplate = itemTemplate
                        workOrderConfiguratorViewController.configuratorDelegate = self
                        
                        if let cs = self.clinicalStatus{
                            workOrderConfiguratorViewController.clinicalStatus = cs
                        }
                        
                        let technicalDataViewController = self.storyboard?.instantiateViewController(withIdentifier: "technicalDataViewController") as! TechnicalDataViewController
                        let technicalDataSecondViewController = self.storyboard?.instantiateViewController(withIdentifier: "technicalDataSecondViewController") as! TechnicalDataSecondViewController
                        
                        let woGlassesConfiguratorTabBarController = self.storyboard?.instantiateViewController(withIdentifier: "WOGlassesConfiguratorTabBarController") as! WOGlassesConfiguratorTabBarController
                        woGlassesConfiguratorTabBarController.workOrderConfiguratorViewController = workOrderConfiguratorViewController
                        woGlassesConfiguratorTabBarController.technicalDataViewController = technicalDataViewController
                        woGlassesConfiguratorTabBarController.technicalDataSecondViewController = technicalDataSecondViewController
                        
                        self.navigationController?.pushViewController(woGlassesConfiguratorTabBarController, animated: true)
                    }
                }
            }
        }
        else if item.isKind(of: DiscountCauses.self){
            let discountCause = item as! DiscountCauses
            if let cartItem = self.changeDiscountForOrderDetail{
                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)
    }
    
    func addNewContactLenses(){
        State.LoadLastClinicalStatus(State.workOrder.contact.ContactId, prescriptionType: "CL") { result in
            if let cs = result {
                self.clinicalStatus = cs
                if self.clinicalStatus != nil && self.clinicalStatus?.PrescriptionType == "CL"{
                    //ToDo
                }
                else{
                    Util.GeneralAlert(viewController: self, message: Util.getString("This contact has no prescription"))
                }
            }else{
                Util.GeneralAlert(viewController: self, message: Util.getString("This contact has no prescription"))
            }
        }
    }
    
    @IBAction func btSendSMS_Click(_ sender: Any) {
        var isSMSAlreadySent: Bool = false
        
        for orderAction in State.workOrder.OrderAction{
            if orderAction.ActionType == "SMS"{
                isSMSAlreadySent = true
                break;
            }
        }
        
        if isSMSAlreadySent{
            Util.AlertYesNo(viewController: self, title: "iPOS", message: Util.getString("AnSMSIsAlreadySent"), actionYes: self.sendSMS, actionNo: { return })
        }
        else{
            self.sendSMS()
        }
    }
    
    func sendSMS(){
        let smsViewController = (self.storyboard?.instantiateViewController(withIdentifier: "WorkOrderSMSViewController") as! WorkOrderSMSViewController)
        smsViewController.navigationItem.setHidesBackButton(true, animated:true);
        smsViewController.orderId = State.workOrder.OrderId
        smsViewController.orderDetailId = self.selectedOrderDetail?.OrderDetailId ?? ""
        smsViewController.delegate = self
        
        if let phoneNumber = State.workOrder.contact.Mobile{
            smsViewController.phoneNumber = phoneNumber
        }
        self.navigationController?.pushViewController(smsViewController, animated: true)
    }
    
    func smsFinished() {
        self.navigationController?.popViewController(animated: true)
    }
    
    @IBAction func keyboardSearchButton(_ 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()
        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.processNone(decodeBarcodeResult: decodeBarcodeResult, barcode: barcode)
                break
            case .FidelityCard:
                print("FidelityCard")
                self.processNone(decodeBarcodeResult: 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.processNone(decodeBarcodeResult: decodeBarcodeResult, barcode: barcode)
                break
            }
        })
    }
    
    func saveConfigurator() {
        self.printTotals()
        self.calculateTotals()
    }
    
    func addOrderDetailDiscountOutsideConfigurator(orderDetail: inout WorkOrderDetail, discountCauseId: Int, discountValue: Double,  discountType: enumDiscountTypes, promotionId: Int?){
        
        if discountValue == 0{
            return
        }
        
        let discount = WorkOrderDetailDiscounts()
        
        discount.OrderDetailId = UUID.init(uuidString: orderDetail.OrderDetailId)!
        discount.DiscountCauseId = discountCauseId
        discount.DiscountType = discountType.rawValue
        discount.DiscountValue = discountValue
        discount.PromotionId = promotionId
        
        if orderDetail.discounts == nil{
            orderDetail.discounts = []
        }
        
        orderDetail.discounts?.append(discount)
        
        let discountValue = orderDetail.OrderedQuantity * discountValue
        if orderDetail.getNumberOfChild() > 0 && discountType != .FK {
            self.distributeDiscountOnChildren(glasses: orderDetail, discountValue: discountValue, discountType: discountType, discountCauseId: discountCauseId, promotionId: promotionId)
        }
    }
    
    func clearOrderDetailDiscountOutsideConfigurator(orderDetail: inout WorkOrderDetail, discountType: enumDiscountTypes){
        if let discounts = orderDetail.discounts{
            for discount in discounts{
                if discount.DiscountType == discountType.rawValue{
                    orderDetail.discounts?.removeAll(where: {$0.OrderDiscountId == discount.OrderDiscountId})
                    if orderDetail.DiscountValue != nil {
                        orderDetail.DiscountValue! -= discount.DiscountValue!
                        
                        orderDetail.NetRowValueVatIncluded = (orderDetail.OrderedQuantity * orderDetail.GrossUnitValueVatIncluded) - orderDetail.DiscountValue!
                        if let vatRate = orderDetail.VatRate {
                            let netValueVatExcluded = (orderDetail.NetRowValueVatIncluded / (1 + vatRate)).rounded(toPlaces: 2)
                            orderDetail.VatValue =  (netValueVatExcluded * vatRate).rounded(toPlaces: 2)
                        }
                    }
                }
            }
        }
        
        let childs = State.workOrder.getChildCollection(parentId: orderDetail.OrderDetailId)
        for var child in childs{
            self.clearOrderDetailDiscountOutsideConfigurator(orderDetail: &child, discountType: discountType)
        }
    }
    
    func printTotals(){
        print(State.workOrder.GrossValueVatIncluded)
        print(State.workOrder.DiscountValue ?? 0)
        print(State.workOrder.NetValueVatIncluded)
        for detail in State.workOrder.OrderDetail{
            print("\(detail.RowType ?? "") - Gross: \(detail.grossRowValueVatIncluded) Discount: \(detail.DiscountValue ?? 0) Net:\(detail.NetRowValueVatIncluded)")
        }
    }
    
    func isValidForLottery() -> Bool{
        let clearCodeMessage = "Cancella il codice della lotteria prima di effettuare la vendita."
        if State.workOrder.NetValueVatIncluded < 1 {
            Util.AlertOperationNotAllowed(viewController: self, message: "Valore totale scontrino deve essere maggiore di 1 EUR per participare alla lotteria! \(clearCodeMessage)")
            return false
        }
        
        if State.workOrder.contact.IsLegalPerson == true{
            Util.AlertOperationNotAllowed(viewController: self, message: "Il contatto associato alla vendita deve essere una persona individuale! \(clearCodeMessage)")
            return false
        }
        
        if State.workOrder.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 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 resetLotteryCode(){
        State.lotteryCode = nil
        self.tfLotteryCode.text = ""
    }
    
    func setLotteryCode(lotteryCode: String){
        State.lotteryCode = lotteryCode.uppercased()
        self.tfLotteryCode.text = lotteryCode.uppercased()
    }
}
