//
//  PriceChangeDialog.swift
//  iPOS
//
//  Created by Apple iMac on 17/05/2018.
//  Copyright © 2018 BBC. All rights reserved.
//

import Foundation

protocol PriceChangeDelegate{
    func onApplay(result: PriceChangeResult)
    func onClear(result: PriceChangeResult)
    func onCancel()
}

class PriceChangeDialog{
    var alert: UIAlertController
    var item: PriceChangeItem
    let delegate: PriceChangeDelegate
    
    let newPriceTextFieldTag: Int = 0
    let percentageDiscountTextFieldTag: Int = 1
    let valueDiscountTextFieldTag: Int = 2
    
    init(item: PriceChangeItem, delegate: PriceChangeDelegate){
        self.alert = UIAlertController(title: Util.getString("Change price or discount"), message: "\(item.name)\n\(item.code)", preferredStyle: .alert)
        self.item = item
        self.delegate = delegate
        self.setAlert()
    }
    
    func setAlert(){
        let currentUnitPrice = self.item.netRowValue / self.item.quantity
        let currentUnitDiscount = self.item.discountValue / self.item.quantity
        
        self.alert.addTextField { (textField) in
            let text: String = Util.getString("Price") + " \(settings.userSettings.defaultCurrency)"
            let placeholder: String = "\(Util.DoubleToStringWithPointSeparator(currentUnitPrice))" + "\(settings.userSettings.defaultCurrency)"
            self.setTextField(textField: textField, text: text, placeholder: placeholder, tag: self.newPriceTextFieldTag)
        }
        
        self.alert.addTextField { (textField) in

            textField.autocorrectionType = .no
            textField.autocapitalizationType = .none
            
            let text: String = Util.getString("Discount") + " %"
            var placeholder: String = ""
            if currentUnitDiscount > 0 {
                placeholder = "\(Util.DoubleToStringWithPointSeparator(100 / (self.item.grossUnitValue / currentUnitDiscount))) %"
            }
            else {
                placeholder = "\(Util.DoubleToStringWithPointSeparator(0)) %"
            }
            self.setTextField(textField: textField, text: text, placeholder: placeholder, tag: self.percentageDiscountTextFieldTag)
        }
        
        self.alert.addTextField { (textField) in
            let text: String = Util.getString("Discount") + " \(settings.userSettings.defaultCurrency)"
            let placeholder: String = "\(Util.DoubleToStringWithPointSeparator(currentUnitDiscount))" + "\(settings.userSettings.defaultCurrency)"
            self.setTextField(textField: textField, text: text, placeholder: placeholder, tag: self.valueDiscountTextFieldTag)
        }
        
        self.alert.addAction(UIAlertAction(title: Util.getString("Apply"), style: .default, handler: { [weak alert] (_) in
            let newPrice = alert?.textFields![0].text!
            let newPercentDiscount = alert?.textFields![1].text!
            let newUnitDiscount = alert?.textFields![2].text!
            if newPrice != "" || newPercentDiscount != "" || newUnitDiscount != ""{
                if let price = Double(newPrice!)?.rounded(toPlaces: 2){
                    if let unitDiscount = Double(newUnitDiscount!)?.rounded(toPlaces: 2){
                        let result: PriceChangeResult = PriceChangeResult(item: self.item)
                        if self.item.grossUnitValue >= price{
                            result.netRowValueVatIncluded = price
                        }
                        else{
                            result.grossUnitValueVatIncluded = price
                        }
                        result.discountValue = unitDiscount * self.item.quantity
                        result.discountPercentage = Double(newPercentDiscount!)!.rounded(toPlaces: 2)
                        result.effectCategory = "PD%"
                        result.canApplyPromotions = false
                        self.delegate.onApplay(result: result)
                    }
                }
            }
        }))
        self.alert.addAction(UIAlertAction(title: Util.getString("Clear"), style: .default, handler: {(_) in
            let result: PriceChangeResult = PriceChangeResult(item: self.item)
            result.grossUnitValueVatIncluded = self.item.originalPrice
            result.discountValue = 0
            result.netRowValueVatIncluded = self.item.originalPrice
            result.canApplyPromotions = true
            self.delegate.onClear(result: result)
        }))
        self.alert.addAction(UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler: {(_) in
            self.delegate.onCancel()
        }))
    }
    
    func setTextField(textField: UITextField, text: String, placeholder: String, tag: Int){
        textField.autocorrectionType = .no
        textField.autocapitalizationType = .none
        textField.tag = tag
        textField.keyboardType = UIKeyboardType.numbersAndPunctuation
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 22))
        label.textAlignment = NSTextAlignment.right
        label.textColor = UIColor(red: 0.78, green: 0.78, blue: 0.80, alpha: 1.0)
        label.text = text
        textField.rightView = label
        textField.rightViewMode = .always
        textField.placeholder = placeholder
        textField.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged)
    }
    
    @objc func textFieldDidChange(_ textField: UITextField) {
        //textField.tag
        self.alert.actions[0].isEnabled = true
        
        if textField.tag == self.newPriceTextFieldTag{
            if let newPrice = self.alert.textFields?[0].text{
                if newPrice != ""{
                    let newPriceValue = Util.checkNumberOfDecimalPlaces(string: newPrice)
                    textField.text = newPriceValue
                    if let price = Double(newPriceValue){
                        //if price >= 0{
                        let minPrice = item.grossUnitValue - (item.discountCause.maxDiscount * item.grossUnitValue)
                        if price >= 0 && price >= minPrice{
                            if item.grossUnitValue >= price{
                                let discountPercentValue = 100 / (item.grossUnitValue / (item.grossUnitValue - price))
                                let discountValue = item.grossUnitValue - price
                                self.alert.textFields?[1].text = "\(Util.DoubleToStringWithPointSeparator(discountPercentValue))"
                                self.alert.textFields?[2].text = "\(Util.DoubleToStringWithPointSeparator(discountValue))"
                            }
                            else{
                                self.alert.textFields?[1].text = "\(Util.DoubleToStringWithPointSeparator(0))"
                                self.alert.textFields?[2].text = "\(Util.DoubleToStringWithPointSeparator(0))"
                            }
                        }
                        else{
                            self.alert.actions[0].isEnabled = false
                            self.alert.textFields?[1].text = ""
                            self.alert.textFields?[2].text = ""
                        }
                    }
                    else{
                        self.alert.actions[0].isEnabled = false
                        self.alert.textFields?[1].text = ""
                        self.alert.textFields?[2].text = ""
                    }
                }
                else{
                    self.alert.textFields?[1].text = ""
                    self.alert.textFields?[2].text = ""
                }
            }
        }
        else if textField.tag == self.percentageDiscountTextFieldTag{
            if let newPercentDiscount = self.alert.textFields?[1].text{
                if newPercentDiscount != ""{
                    let newPercentDiscountValue = Util.checkNumberOfDecimalPlaces(string: newPercentDiscount)
                    textField.text = newPercentDiscountValue
                    if let percentDiscount = Double(newPercentDiscountValue){
                        let maxPercentDecimalValue = item.discountCause.maxDiscount * 100
                        if percentDiscount >= 0 && percentDiscount <= maxPercentDecimalValue{
                            let unitDiscountPercent = percentDiscount / 100
                            let discountValue = item.grossUnitValue - Util.applyDiscount(grossValue: item.grossUnitValue, discountPercent: unitDiscountPercent)
                            let newPrice = (item.grossUnitValue - discountValue).rounded(toPlaces: 2)
                            self.alert.textFields?[0].text = "\(Util.DoubleToStringWithPointSeparator(newPrice))"
                            self.alert.textFields?[2].text = "\(Util.DoubleToStringWithPointSeparator(discountValue))"
                        }
                        else if percentDiscount < 0 {
                            self.alert.textFields?[0].text = "\(Util.DoubleToStringWithPointSeparator(item.grossUnitValue))"
                            self.alert.textFields?[1].text = "\(Util.DoubleToStringWithPointSeparator(0))"
                            self.alert.textFields?[2].text = "\(Util.DoubleToStringWithPointSeparator(0))"
                        }
                        else{
                            let newPrice = item.grossUnitValue - ((item.grossUnitValue * maxPercentDecimalValue) / 100)
                            let discountValue = (item.grossUnitValue * maxPercentDecimalValue) / 100
                            self.alert.textFields?[0].text = "\(Util.DoubleToStringWithPointSeparator(newPrice))"
                            self.alert.textFields?[1].text = "\(Util.DoubleToStringWithPointSeparator(maxPercentDecimalValue))"
                            self.alert.textFields?[2].text = "\(Util.DoubleToStringWithPointSeparator(discountValue))"
                        }
                    }
                    else{
                        self.alert.actions[0].isEnabled = false
                        self.alert.textFields?[0].text = ""
                        self.alert.textFields?[2].text = ""
                    }
                }
                else{
                    self.alert.textFields?[0].text = ""
                    self.alert.textFields?[2].text = ""
                }
            }
        }
        else if textField.tag == self.valueDiscountTextFieldTag{
            if let newValueDiscount = self.alert.textFields?[2].text{
                if newValueDiscount != ""{
                    let newValueDiscountValue = Util.checkNumberOfDecimalPlaces(string: newValueDiscount)
                    textField.text = newValueDiscountValue
                    if let valueDiscount = Double(newValueDiscountValue){
                        //if valueDiscount >= 0 && valueDiscount <= item.grossUnitValue{
                        let maxValueDiscount = item.discountCause.maxDiscount * item.grossUnitValue
                        if valueDiscount >= 0 && valueDiscount <= maxValueDiscount{
                            let newPrice = item.grossUnitValue - valueDiscount
                            let discountPercentValue = 100 / (item.grossUnitValue / valueDiscount)
                            self.alert.textFields?[0].text = "\(Util.DoubleToStringWithPointSeparator(newPrice))"
                            self.alert.textFields?[1].text = "\(Util.DoubleToStringWithPointSeparator(discountPercentValue))"
                        }
                        else if valueDiscount < 0 {
                            self.alert.textFields?[0].text = "\(Util.DoubleToStringWithPointSeparator(item.grossUnitValue))"
                            self.alert.textFields?[1].text = "\(Util.DoubleToStringWithPointSeparator(0))"
                            self.alert.textFields?[2].text = "\(Util.DoubleToStringWithPointSeparator(0))"
                        }
                        else{
                            let newPrice = item.grossUnitValue - maxValueDiscount.rounded(toPlaces: 2)
                            let discountValue = (maxValueDiscount * 100) / item.grossUnitValue
                            self.alert.textFields?[0].text = "\(Util.DoubleToStringWithPointSeparator(newPrice))"
                            self.alert.textFields?[1].text = "\(Util.DoubleToStringWithPointSeparator(discountValue))"
                            self.alert.textFields?[2].text = "\(Util.DoubleToStringWithPointSeparator(maxValueDiscount))"
                            
                            /*self.alert.textFields?[0].text = "\(Util.DoubleToStringWithPointSeparator(0))"
                            self.alert.textFields?[1].text = "\(Util.DoubleToStringWithPointSeparator(100))"
                            self.alert.textFields?[2].text = "\(Util.DoubleToStringWithPointSeparator(item.grossUnitValue))"
                             */
                        }
                    }
                    else{
                        self.alert.actions[0].isEnabled = false
                        self.alert.textFields?[0].text = ""
                        self.alert.textFields?[1].text = ""
                    }
                }
                else{
                    self.alert.textFields?[0].text = ""
                    self.alert.textFields?[1].text = ""
                }
            }
        }
    }
    
    func show(viewController: UIViewController){
        viewController.present(alert, animated: true, completion: nil)
    }
}
