//
//  ConfirmOrderView.swift
//  NSApplication1.8
//
//  Created by Amine  on 5/10/20.
//  Copyright © 2020 Amine. All rights reserved.
//

import Foundation
import UIKit
import SwiftyJSON

class ConfirmOrderView : OrderSimpleView, CouponInputDialogLauncherDelegate{
   

    @IBOutlet weak var stackView: UIStackView!
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    @IBOutlet weak var scrollView: UIScrollView!
    
    
    override func setup() {
        
         
       
     }
    
    
    var details: [String: String]?
    
    func setupView() {
        
        guard stackView.subviews.count == 0 else {
            return
        }
    
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.distribution = .fillProportionally
        
    }
    
    var total = 0.0
    var total_currency: Currency? = nil
    var orderCart: [[String: Any]] = []
    
    
    func updateDetail(parameters: [KeyValue],cart: Cart){
     
       
        
        self.productList = []
        
        stackView.removeAllArrangedSubviews()
        
        let order_details = UILabel.new(label_text: "Order Details")
        order_details.initBolodFont(size: 18)
        
        stackView.addArrangedSubview(order_details)
        
        for field in parameters{
            
            if(field.value == ""){
                let label = UILabel.newKV(label_text: field.key, label_value: "--")
                stackView.addArrangedSubview(label)
            }else{
                if field.key == "Address"{
                    
                    let address_arr = field.value.split(separator: ";")
                    let address: String = String(address_arr[0])
                    
                    let label = UILabel.newKV(label_text: field.key, label_value: address)
                    stackView.addArrangedSubview(label)
                    
                }else{
                    let label = UILabel.newKV(label_text: field.key, label_value: field.value)
                    stackView.addArrangedSubview(label)
                }
               
            }
            
        }
        
        
        let order_products = UILabel.new(label_text: "Order Product")
        order_products.initBolodFont(size: 18)
        stackView.addArrangedSubview(order_products)
    
        //calculate total
        total = 0.0
        total_currency = nil
        
        
        for item in cart.items{
            
       
            var amount_v = Float(item.amount)
            var amount_s = String(item.amount)
            if item.item!.product_type == "price" {
                     
                if let currency = item.item!.currency {
                    if let pprice = currency.parseCurrencyFormat(price: Float(item.amount) * Float(item.qty)){
                        amount_s = pprice
                        total_currency = currency
                        total = Double((Float(item.amount) * Float(item.qty))) + total
                    }
                }
                     
            }else{
                amount_v = 0.0
                amount_s = "0.0"
            }
            
           
        
            
            
            var image_url = ""
            
            if let img = item.item!.listImages.first{
                image_url = img.url200_200
            }
            
            let p = ProductLineItem(
                id: item.item!.id,
                module: "product",
                image_url: image_url,
                name: item.item!.name,
                desc: item.item!._description,
                amount_s: String(describing: amount_s),
                amount_v: Double(amount_v),
                qty: Double(item.qty),
                variants: item.variants.toArray()
            )
            
            
            orderCart.append([
                "item_id":item.item!.id,
                "amount": Float(item.amount) * Float(item.qty),
            ])
            
            let pl = ProductLine.newInstance().setup(product: p)
            let line_size = ( 40  +  (12 * getLineSize(variants: item.variants.toArray()) ) )
            pl.desc.text = pl.desc.text! + getLineDescription(variants: item.variants.toArray())
            pl.heightAnchor.constraint(equalToConstant: CGFloat(line_size)).isActive = true
            
            stackView.addArrangedSubview(pl)
            
            productList.append(p)
        }
        
        
        
        //setup coupon
        setupCouponView()
      
        
    }
    
   
    lazy var couponDialogLauncher: CouponInputDialogLauncher = {
          let launcher = CouponInputDialogLauncher()
         // launcher.mainController = self
          return launcher
      }()
    
    var orderCouponLabel: UILabel?
    var orderCouponLabelValue: UILabel?
    
    func setupCouponView() {
      
        // let order_coupon = CouponView.newInstance()
        if orderCouponLabel == nil && orderCouponLabelValue == nil{
            let order_coupon = UIStackView.col2_labelView(text: "Coupon".localized, value: "Add Coupon")
            order_coupon.heightAnchor.constraint(equalToConstant: CGFloat(40)).isActive = true
            stackView.addArrangedSubview(order_coupon)
           orderCouponLabel = order_coupon.arrangedSubviews[0] as? UILabel
           orderCouponLabelValue = order_coupon.arrangedSubviews[1] as? UILabel
        }
        
        orderCouponLabel?.text = "Coupon".localized
        orderCouponLabelValue?.text = "Add Coupon".localized
        
    
        let icon = UIImage.init(icon: .fontAwesomeSolid(.plus), size: CGSize(width: 18, height: 18), textColor:  Colors.primaryColor)
        orderCouponLabelValue?.setLeftIcon(image: icon)
        
        orderCouponLabelValue?.textAlignment = .right
        orderCouponLabelValue?.textColor = Colors.primaryColor
    
        let gestureRecognizerAddCoupon = BindableGestureRecognizer {
            self.couponDialogLauncher.delegate = self
            self.couponDialogLauncher.show()
        }
        
        
        orderCouponLabelValue!.isUserInteractionEnabled = true
        orderCouponLabelValue!.addGestureRecognizer(gestureRecognizerAddCoupon)
         
        
    }
    
    func onCouponApply(code: String) {
        
        let jsonData = JSON(self.orderCart)
        guard let jsonString = jsonData.rawString() else{
            return
        }
    
        let api  = SimpleRequestApi()
        
        let parameters = [
            "code":code,
            "cart":jsonString,
        ]
        
        MyProgress.show()
        
        api.run(url: Constances.Api.API_APPLY_COUPON, parameters: parameters) { parser in
           
            if let p = parser, p.success == 1, let result = p.result{
                Utils.printDebug("\(result)")
                self.codeCoupn = code
                self.parseDiscountedItems(code: code,json: result)
                
            }
            
            MyProgress.dismiss()
           
        }
        
    }
    
    
    var codeCoupn: String?
    var appliedDiscountedValue0: Double?
    
    func parseDiscountedItems(code: String, json: JSON){
        
        var newOrderTotalPrice:Double = 0;
        var TotalOfPercent:Int = 0;
        var appliedDiscountedValue:Double = 0;

        for (_, item) in json {
            
            let amount = item["amount"].doubleValue
            let discount0 = item["discount"].intValue
            let discountedAmount = item["discountedAmount"].doubleValue
            
            newOrderTotalPrice = newOrderTotalPrice+amount
            TotalOfPercent = TotalOfPercent + discount0
            appliedDiscountedValue = appliedDiscountedValue+discountedAmount
            
        }
        
        self.appliedDiscountedValue0 = appliedDiscountedValue
        
        orderCouponLabel?.text  = "\("Coupon".localized): \(code) (\(TotalOfPercent)%)"
        
        
        //IUpdate label
        if let currency = total_currency{
            if let pprice = currency.parseCurrencyFormat(price: Float(appliedDiscountedValue)){
                orderCouponLabelValue?.text = "-\(pprice)"
            }
        }
     
   
        //Updtae button
        let icon = UIImage.init(icon: .fontAwesomeSolid(.trash), size: CGSize(width: 18, height: 18), textColor:  UIColor.red)
        orderCouponLabelValue?.setRightIcon(image: icon)
        orderCouponLabelValue?.textAlignment = .right
        orderCouponLabelValue?.textColor = Colors.primaryColor
        
    
        let gestureRecognizerRemoveCoupon = BindableGestureRecognizer {
            self.codeCoupn = nil
            self.setupCouponView()
        }
        
        orderCouponLabelValue!.isUserInteractionEnabled = true
        orderCouponLabelValue!.addGestureRecognizer(gestureRecognizerRemoveCoupon)
    
    }
    
    
    var productList: [ProductLineItem] = []
    
    
    func getLineSize(variants: [V_GroupResult]) -> Int{
        
        var count = 0
        
        for g in variants{
            count = count + 1
            count = count + g.options.count
        }
        
        return count
    }
    
    func getLineDescription(variants: [V_GroupResult]) -> String{
        
        var text = "\n"
        
        for g in variants{
            text = text+"\(g.grp_label): \n"
            for o in g.options {
                text = text+"   -\(o.label)\n"
            }
           
        }
        
        Utils.printDebug("\(variants)")
        
        return text
    }

}


extension UILabel{
    
    static func newKV(label_text: String, label_value: String) -> UILabel {
        
        let my_label_text = UILabel()
        my_label_text.initDefaultFont(size: 14)
        my_label_text.numberOfLines = 0
        my_label_text.text = ""
        
        let html = "<b>\(label_text): </b> "+label_value
        my_label_text.attributedText = html.toHtml().attributedString
        
        return my_label_text
    }
    
    static func new(label_text: String) -> UILabel {
           let my_label_text = UILabel()
           my_label_text.initDefaultFont(size: 14)
           my_label_text.numberOfLines = 0
           my_label_text.text = label_text
           return my_label_text
       }
}


extension UIStackView {
    
    func removeAllArrangedSubviews() {
        
        let removedSubviews = arrangedSubviews.reduce([]) { (allSubviews, subview) -> [UIView] in
            self.removeArrangedSubview(subview)
            return allSubviews + [subview]
        }
        
        // Deactivate all constraints
        NSLayoutConstraint.deactivate(removedSubviews.flatMap({ $0.constraints }))
        
        // Remove the views from self
        removedSubviews.forEach({ $0.removeFromSuperview() })
    }
}

