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

import Foundation
import Alamofire

class ShoppingCart {
    var cartItems: [ShoppingCartItem]
    var grossValue: Double
    var discountValue: Double
    var netValue: Double
    var quantity: Double
    var payments: [Payment] = [Payment]()
    var isRecalculated:Bool = false
    var lastItemAdded: ShoppingCartItem = ShoppingCartItem()
    var lastItemRemoved: ShoppingCartItem = ShoppingCartItem()
    var isItemAdded: Bool? = nil
    var allowSendToHealthInsurance: Bool?
    var change: Double = 0
    var totalPayed: Double = 0
    var effects: [Effect]?
    var usedPoints: Int?
    var vouchers: [CartVouchers] = []
    var fidelityCard: FidelityCard?
    var contact: Contact?
    var vouchersInfo: [VoucherInfo] = []
    var receiptLines: String?
    var receiptType: String = ""
    var effectVouchers: [EffectVoucher] = []
    var lastPromoEngineResponse: PromoEngineResponse? // temp fix for non valid voucher    

    init() {
        self.cartItems = [ShoppingCartItem]()
        self.grossValue = 0
        self.discountValue = 0
        self.netValue = 0
        self.quantity = 0
        self.effectVouchers = [EffectVoucher]()
    }
    
    var gainedPoints: Int{
        get{
            var gainedPoints = 0
            if self.fidelityCard != nil && self.fidelityCard?.cardInfo != nil{
                if let spendAmountForPoint = self.fidelityCard?.fidelityCardType?.spendAmountForPoint{
                    gainedPoints = Int(self.netValue / spendAmountForPoint)
                }
            }
            return gainedPoints
        }
    }
    
    func addItem(barcodeInfo: WSBarcodeInfo){
//        for cartItem in self.cartItems{
//            if cartItem.barcodeInfo.Barcode == barcodeInfo.Barcode && !barcodeInfo.hasSerialNumber{
//                if cartItem.DiscountValue > 0{
//                    let unitDiscount = cartItem.DiscountValue / cartItem.Quantity
//                    cartItem.DiscountValue = unitDiscount * (cartItem.Quantity + 1)
//                }
//                cartItem.Quantity += 1
//                lastItemAdded = cartItem
//                isItemAdded = true
//                return
//            }
//        }
        let item = ShoppingCartItem()
        item.barcodeInfo = barcodeInfo
        item.GrossUnitValue = barcodeInfo.SalePrice
        item.NetRowValue = barcodeInfo.SalePrice
        item.Quantity = barcodeInfo.quantity
        item.RowNumber = cartItems.count + 1
        item.fiscalExpenseTypeId = barcodeInfo.FiscalExpenseTypeId
        item.fiscalExpenseTypeCode = barcodeInfo.FiscalExpenseTypeCode
        item.serialNumber = barcodeInfo.serialNumber
        
        self.lastItemAdded = item
        self.isItemAdded = true
        self.cartItems.append(item)
    }
    
    func removeItem(at: Int){
        self.isItemAdded = nil
        self.lastItemRemoved = cartItems[at]
        self.cartItems.remove(at: at)
        for i in 0..<cartItems.count{
            self.cartItems[i].RowNumber = i + 1
        }
    }
    
    func setCanApplyPromotions(){
        if self.vouchersInfo.count > 0 {
            for voucher in self.vouchersInfo{
                if voucher.generator.cumulative == false{
                    for item in self.cartItems{
                        item.canApplyPromotions = false
                    }
                }
                return
            }
        }
    }
    
    func recalculate(completionHandler: @escaping () -> Void){
        self.grossValue = 0
        self.netValue = 0
        self.quantity = 0

        self.setCanApplyPromotions()
        let promoCart = createPromoShoppingCart()
        
        State.ApplyPromoEngine(promoCart: promoCart, completionHandler: { promoEngineResponse in
            self.lastPromoEngineResponse = promoEngineResponse
            self.importPromoShoppingCart(promoEngineResponse.shoppingCart)
            self.isRecalculated = true
            
            if self.isItemAdded == nil {
                let firstLine = Util.getString("Total").uppercased()
                let secondLine = "\(settings.userSettings.currencyId) \(Util.DoubleToString(State.shoppingCart.netValue))"
                settings.customerDisplay?.showCustomerDisplay(line1: firstLine, line2: secondLine)
            }
            else{
                let firstLine = self.lastItemAdded.barcodeInfo.Name
                let secondLine = "\(settings.userSettings.currencyId) \(Util.DoubleToString(self.lastItemAdded.NetRowValue))"
                settings.customerDisplay?.showCustomerDisplay(line1: firstLine, line2: secondLine)
            }
            
            completionHandler()
        })
    }

    func importPromoShoppingCart(_ promoShoppingCart: PromoShoppingCart )  {
        
        for rowNumber in 0..<promoShoppingCart.items.count {
            let item = self.cartItems[rowNumber]
            let promoItem = promoShoppingCart.items[rowNumber]
            item.GrossUnitValue = promoItem.grossUnitValueVatIncluded!
            item.DiscountValue = promoItem.rowDiscountValue!
            item.DiscountPercentage = ((item.DiscountValue /  item.GrossUnitValue) * 100).rounded(toPlaces: 2)
            item.NetRowValue = promoItem.netRowValueVatIncluded!
            item.PromotionId = nil
            item.DistributedDiscount = promoItem.distributedDiscount
            
            item.Effects?.removeAll(where: {$0.isManualDiscount == false})
            
            if let promoEffects = promoItem.effects {
                if promoEffects.count > 0 {
                    item.PromotionId = promoEffects[0].promotionId
                }
                
                for effect in promoEffects{
                    effect.rowDiscountPercent = (((item.DiscountValue /  item.GrossUnitValue) / item.Quantity) * 100).round(nearest: 2)
                    
                    if item.Effects == nil {
                        item.Effects = []
                    }
                    
                    item.Effects?.append(effect)
                }
            }
            
            print("Effects: \(item.barcodeInfo.Name) \(item.Effects?.count ?? 0)")
            
            self.grossValue += item.GrossUnitValue
            self.netValue += item.NetRowValue - item.DistributedDiscount
            self.quantity += item.Quantity
        }
        self.vouchers = promoShoppingCart.vouchers
        self.effects = promoShoppingCart.effects
        self.usedPoints = promoShoppingCart.usedPoints
        self.effectVouchers = promoShoppingCart.effectVouchers
        
    }
    
    func createPromoCartVouchers(promoCart: PromoShoppingCart){
        promoCart.vouchers = []
        for voucherInfo in self.vouchersInfo{
            let cartVouchers = CartVouchers()
            cartVouchers.voucherCode = voucherInfo.voucherCode
            cartVouchers.amount = voucherInfo.amount
            promoCart.vouchers.append(cartVouchers)
        }
    }

    func createPromoShoppingCart() -> PromoShoppingCart {
        let promoCart = PromoShoppingCart()
        promoCart.storeId = State.storeId
        promoCart.cashRegister = State.cashRegister
        promoCart.payments = self.payments
        promoCart.allowSendToHealthInsurance = self.allowSendToHealthInsurance
        promoCart.effects = self.effects
        promoCart.usedPoints = self.usedPoints
        self.createPromoCartVouchers(promoCart: promoCart)
        promoCart.receiptLines = self.receiptLines
        promoCart.receiptType = self.receiptType
        promoCart.effectVouchers = self.effectVouchers
        if let contact = self.contact{
            promoCart.contactId = UUID.init(uuidString: contact.ContactId)
        }
        else{
            promoCart.contactId = nil
        }
        
        if let fidelity = State.shoppingCart.fidelityCard{
            promoCart.fidelityCardId = UUID.init(uuidString: fidelity.contactId)
            
            promoCart.paybackCard = PaybackCard()
            promoCart.paybackCard?.cardNumber = fidelity.cardBarcode
            promoCart.paybackCard?.fidelityCardId = UUID.init(uuidString: fidelity.contactId)
        }
        
        for item in self.cartItems {
            let promoItem = PromoCartItem()
            promoItem.rowNumber = item.RowNumber
            promoItem.productCode = item.barcodeInfo.Code
            promoItem.productName = item.barcodeInfo.Name
            promoItem.styleId = item.barcodeInfo.StyleId
            promoItem.vatId = item.barcodeInfo.VatId
            promoItem.newVatRate = item.barcodeInfo.VatRate!
            promoItem.originalVatRate = item.barcodeInfo.VatRate!
            promoItem.barcode = item.barcodeInfo.Barcode
            promoItem.productFamilyName = item.barcodeInfo.productFamilyName
            promoItem.productFamilyCode = item.barcodeInfo.productFamilyCode
            promoItem.productSubfamilyName = item.barcodeInfo.productSubfamilyName
            promoItem.productSubfamilyCode = item.barcodeInfo.productSubfamilyCode
            
            //Used for calculating the promotions
            promoItem.originalUnitValueVatIncluded = Decimal(item.barcodeInfo.SalePrice)
            
            //Used to save the transaction. Not used by promo engine
            promoItem.grossUnitValueVatIncluded = item.GrossUnitValue
            promoItem.rowDiscountValue = item.DiscountValue
            promoItem.distributedDiscount = item.DistributedDiscount
            promoItem.netRowValueVatIncluded = item.NetRowValue
            
            promoItem.quantity = item.Quantity
            promoItem.canApplyPromotions = item.canApplyPromotions
            promoItem.fiscalExpenseTypeId = item.fiscalExpenseTypeId
            promoItem.serialNumber = item.serialNumber
            
            promoItem.effects = [Effect]()
            if let effects = item.Effects {
                promoItem.effects = effects
            }
            
            if item.Quantity < 0{
                promoItem.rowType = TicketRowTypes.ReturnProduct.rawValue.description
            }
            else{
                promoItem.rowType = TicketRowTypes.Product.rawValue.description
            }
        
            promoCart.items.append(promoItem)
        }
        
        
        return promoCart
    }
    
    func isValidForSendingToHI() -> Bool{
        for cartItem in self.cartItems{
            if cartItem.fiscalExpenseTypeId != nil{
                return true
            }
        }
        return false
    }
    
    func applyFidelityPointsDiscount(usedPoints: Int?, discountValue: Double?){
        self.usedPoints = usedPoints
        if usedPoints == nil && discountValue == nil{
            if let effects = self.effects{
                for i in (0..<effects.count).reversed(){
                    if effects[i].discountCauseId == -2{
                        self.effects!.remove(at: i)
                    }
                }
            }
        }
        else{
            if let effects = self.effects{
                var found: Bool = false
                for effect in effects{
                    if effect.discountCauseId == -2{
                        effect.rowDiscountValue = discountValue!
                        found = true
                        break;
                    }
                }
                
                if !found{
                    self.effects = [Effect]()
                    
                    let effect = Effect()
                    effect.discountCauseId = -2
                    effect.rowNumber = (self.effects?.count)! + 1
                    effect.rowDiscountValue = discountValue!
                    
                    self.effects?.append(effect)
                }
            }
            else{
                self.effects = [Effect]()
                
                let effect = Effect()
                effect.discountCauseId = -2
                effect.rowNumber = 1
                effect.rowDiscountValue = discountValue!
                
                self.effects?.append(effect)
            }
        }
    }
    
    func getFidelityPointsDiscount() -> Double{
        var pointsDiscount: Double = 0
        if let effects = State.shoppingCart.effects{
            for effect in effects{
                if effect.discountCauseId == -2{
                    pointsDiscount += effect.rowDiscountValue
                }
            }
        }
        
        return pointsDiscount
    }
    
    func getTotalDistributedDiscount() -> Double{
        var totalDiscount: Double = 0
        
        for item in self.cartItems{
            totalDiscount += item.DistributedDiscount
        }
        
        return totalDiscount
    }
}

class ShoppingCartItem {
    var barcodeInfo: WSBarcodeInfo
    var canApplyPromotions: Bool
    var Quantity: Double
    var GrossUnitValue: Double
    var PromotionId: Int?
    var DiscountValue: Double
    var DiscountPercentage: Double
    var DistributedDiscount: Double
    var NetRowValue: Double
    var RowNumber: Int
    var Effects: [Effect]?
    var fiscalExpenseTypeId: Int?
    var fiscalExpenseTypeCode: String?
    var serialNumber: String?
    var rowTypeId: Int = 1
    
    init() {
        barcodeInfo = WSBarcodeInfo()
        Quantity = 0
        GrossUnitValue = 0
        DiscountValue = 0
        DiscountPercentage = 0
        DistributedDiscount = 0
        NetRowValue = 0
        RowNumber = 1
        canApplyPromotions = true
    }
    
    func convertToPriceChangeItem() -> PriceChangeItem{
        let item: PriceChangeItem = PriceChangeItem()
        item.rowNumber = self.RowNumber
        item.name = self.barcodeInfo.Name
        item.code = self.barcodeInfo.Code
        item.originalPrice = self.barcodeInfo.SalePrice
        item.netRowValue = self.NetRowValue
        item.grossUnitValue = self.GrossUnitValue
        item.quantity = self.Quantity
        item.discountValue = self.DiscountValue
        item.discountPercentage = self.DiscountPercentage
        return item
    }
    
    func importPriceChanges(result: PriceChangeResult){
        self.NetRowValue = result.netRowValueVatIncluded
        self.GrossUnitValue = result.grossUnitValueVatIncluded
        self.DiscountValue = result.discountValue
        self.DiscountPercentage = result.discountPercentage
        self.canApplyPromotions = result.canApplyPromotions
    }
    
    func addEffect(discountCause: DiscountCauses, rowNumber: Int, discountValue: Double, discountPercentage: Double, effectCategory: String){
        let effect = Effect()
        effect.discountCauseId = discountCause.discountCauseId
        effect.rowNumber = rowNumber
        effect.rowDiscountValue = discountValue
        effect.effectCategory = effectCategory
        effect.rowDiscountPercent = discountPercentage
        effect.isManualDiscount = true
                
        self.Effects = [effect]
    }
    
    var vatRate: Double{
        get{
            var vatRate: Double = 0
            if let vr = self.barcodeInfo.VatRate{
                vatRate = vr
            }
            return (vatRate).rounded(toPlaces: 2)
        }
    }
    
    var netRowValueVatExcluded: Double{
        get{
            return (self.NetRowValue / (1 + vatRate)).rounded(toPlaces: 2)
        }
    }
    
    var vatValue: Double{
        get{
            return  (netRowValueVatExcluded * vatRate).rounded(toPlaces: 2)
        }
    }
}
