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

import Foundation
import UIKit
import SwiftIcons
import SwiftyJSON
import RealmSwift

class OrderPaymentView : OrderSimpleView, PaymentMethodDelegate{
    
    

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var mpayments_container: UIStackView!
    @IBOutlet weak var amount_container: UIStackView!
    
    var total = 0.0
    var total_currency: Currency? = nil
    
    
    override func setup() {
        
        if(!ModuleManager.isEnabled(module: "order_payment")){
            return
        }
        
         let realm = try! Realm()
         let list: Results<OrderPayment> = realm.objects(OrderPayment.self)
         self.setupView(list: Array(list))
    
         self.load_payments()
        
       
     }
    
 
    func setupView(list: [OrderPayment]) {
        
      //  mpayments_container.translatesAutoresizingMaskIntoConstraints = false
        mpayments_container.distribution = .fillProportionally
        mpayments_container.spacing = 20
        
      
       addConstraint(NSLayoutConstraint(item: mpayments_container, attribute: .right, relatedBy: .equal, toItem: scrollView, attribute: .right, multiplier: 1, constant: 0))
        
       
        mpayments_container.removeAllArrangedSubviews()
                     
        let order_details = UILabel.new(label_text: "Payment Methods")
        order_details.initBolodFont(size: 18)
        order_details.heightAnchor.constraint(equalToConstant: 40).isActive = true
        mpayments_container.addArrangedSubview(order_details)
        
        
        
        var first = true
        
     
        for op in list{
            
            let method1 = PaymentMethod.newInstance()
            method1.heightAnchor.constraint(equalToConstant: 80).isActive = true
            mpayments_container.addArrangedSubview(method1)
            method1.setup(method: op)
            method1.delegate = self
            
            if(first){
                paymentMethodressed(method: op, view: method1)
                first = false
            }
            
            
        }
    
        
    }
    
    
    
    func updateAmount(total: Double, currency: Currency?) {
        
        if selected_payment == nil{
            
        }
        
        guard let curr = currency else {
            return
        }
        
        
        self.total = total
        self.total_currency = currency
        
        Utils.printDebug("\(total) \(currency)")
        
        amount_container.translatesAutoresizingMaskIntoConstraints = false
        amount_container.distribution = .fillProportionally
        amount_container.spacing = 10
        amount_container.removeAllArrangedSubviews()
        
        
        var calculated_total = total
       
        
        //sub tottal
        
        if let pprice = curr.parseCurrencyFormat(price: Float(total)){
            let am = AmoutView.newInstance().setup(key: "Subtotal", value: pprice)
            am.heightAnchor.constraint(equalToConstant: 30).isActive = true
            amount_container.addArrangedSubview(am)
        }
        
   
        
        if let discount = appliedDiscountedValue0 ,ModuleManager.isEnabled(module: "coupons"), discount > 0{
            
            if let pprice = curr.parseCurrencyFormat(price: Float(discount * -1)){
                let am = AmoutView.newInstance().setup(key: "Discount".localized, value: pprice)
                am.heightAnchor.constraint(equalToConstant: 30).isActive = true
                amount_container.addArrangedSubview(am)
                am.amount_value.textColor = UIColor.red
            }
            
            calculated_total = calculated_total + (discount * -1)
            
            if let pprice = curr.parseCurrencyFormat(price: Float(calculated_total)){
                let am = AmoutView.newInstance().setup(key: "Discounted Subtotal", value: pprice)
                am.heightAnchor.constraint(equalToConstant: 30).isActive = true
                amount_container.addArrangedSubview(am)
            }
        }
        
        
        //sub tax value
        
        var amount_tax = 0.0
              
        if let selected_payment = selected_payment, let tax = selected_payment.tax {
                         
            amount_tax = tax.value
            
            if amount_tax > 0{
                
                amount_tax = ( (Double(tax.value)/100) * calculated_total )
                
                if let price = curr.parseCurrencyFormat(price: Float(amount_tax)){
                    
                    let am = AmoutView.newInstance().setup(key: tax.name, value: price)
                    am.heightAnchor.constraint(equalToConstant: 30).isActive = true
                    amount_container.addArrangedSubview(am)
                    
                    calculated_total =  calculated_total + amount_tax
                    
                }
            
            }
           
        }
        
        //sub delievry fees
        
        let store = Store.findById(id: _store_id);
        
        Utils.printDebug("\(store)")
        
    
        if let dct = SyncAppConfig.findById(id: "DELIVERY_FEES_TYPE")
           , let dcv = SyncAppConfig.findById(id: "DELIVERY_FEES_VALUE"),
           ModuleManager.isEnabled(module: "delivery"), store!.deliveryEnabled == 1 {
            
            if dct.getValue(defaultValue: "disabled") == "fixed"{
                
                let value = dcv.getValue(defaultValue: 0)
                
                if let price = curr.parseCurrencyFormat(price: Float(value)){
                    let am0 = AmoutView.newInstance().setup(key: "Delievry fees".localized, value: "\(price)")
                    am0.heightAnchor.constraint(equalToConstant: 30).isActive = true
                    amount_container.addArrangedSubview(am0)
                }
                
                calculated_total =  calculated_total + Double(value)
               
            }else if dct.getValue(defaultValue: "disabled") == "commission" {
             
                let value = dcv.getValue(defaultValue: 0.0)
                let delivery_fees = ( (value/100) * total )
                
                if let price = curr.parseCurrencyFormat(price: Float(delivery_fees)){
                    let am0 = AmoutView.newInstance().setup(key: "delievry_fees".localized, value: "\(price)" )
                    am0.heightAnchor.constraint(equalToConstant: 30).isActive = true
                    amount_container.addArrangedSubview(am0)
                }
                
                calculated_total =  calculated_total + delivery_fees
            
            }
            
        }
        
        
        Utils.printDebug("\(calculated_total)")
                     
      
        if let curr = currency {
            
            let amount  = calculated_total
            
           
            if let pprice = curr.parseCurrencyFormat(price: Float(amount)){
                            
                let am = AmoutView.newInstance().setup(amount: pprice)
                am.heightAnchor.constraint(equalToConstant: 30).isActive = true
                amount_container.addArrangedSubview(am)
                               
            }
        }
        
    }
    
    
    var codeCoupn: String?
    var appliedDiscountedValue0: Double?
    
    func setDiscount(code: String?, appliedDiscountValue: Double?){
        self.codeCoupn = code
        self.appliedDiscountedValue0 = appliedDiscountValue
    }
  
    var selected_payment: OrderPayment?
    
    func paymentMethodressed(method: OrderPayment, view: PaymentMethod) {
        
         //let nextView = self.order_container.subviews[(page-1)] as! ConfirmOrderView
        
        for v in self.mpayments_container.subviews{
            if(v.isKind(of: PaymentMethod.self)){
                 let _v = v as! PaymentMethod
                _v.image_checked.isHidden = true
                _v.shadow_.backgroundColor = UIColor.gray.withAlphaComponent(0.3)
            }
        }
        
        selected_payment = method
        view.image_checked.isHidden = false
        view.shadow_.backgroundColor = UIColor(red: 0.0/255.0, green: 180.0/255.0, blue: 124.0/255.0, alpha: 1.0)
        
        
        updateAmount(total: total, currency: total_currency)
        
        if  method.id == "10013"{
           
            if let vc = viewController{
                let alert = UIAlertController(title: "Transfer Bank".localized, message: "By selecting bank transfer, you will receive an email to complete the payment.".localized, preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK".localized, style: .default, handler: { action in
                    alert.dismiss(animated: true, completion: nil)
                }))

                vc.present(alert, animated: true)
                
            }
        }
    }
    
    
    func load_payments() {
     
        MyProgress.show(parent: self)

    
         let api = SimpleRequestApi()
         
         var parameters = [
             "init":"true"
         ]
         
         
     
         if let sess = Session.getInstance(), let user = sess.user{
             parameters["user_id"] = "\(user.id)"
         }
         
     
         api.run(url: OrderConstances.Api.API_GET_PAYMENTS, parameters: parameters) { (parser) in
            
            Utils.printDebug("\(parser?.result)")
                
                 if(parser?.success == 1){
                    
                    MyProgress.dismiss()
                    Utils.printDebug("\(parser?.result)")
                    
                    self.parse(json: parser!.result!)
                             
                }else if(parser?.success == -1){
                    
                    Utils.printDebug("\(parser?.result)")
                               
                             
                    if let errors = parser?.errors, errors.count > 0{
                       MyProgress.dismiss()

                    }
                            
                }else if(parser?.success == 0){
                    
                    if !Session.isLogged(){
                        
                    }
                   
                    
                }
                    
        }
        
         
     }
    
    func parse(json: JSON)  {
        
        let parser = OPaymentParser(json: json)
        
        Utils.printDebug("\(parser.parse())")
        
        let list = parser.parse()
        list.saveAll()
        
        self.setupView(list: list)
        
        
        
    }
    
    
    
       func get_payment_url(order_id: Int) {
       
      
           var parameters = [
               "order_id":String(order_id)
           ]
           
           if let sess = Session.getInstance(), let user = sess.user{
               parameters["user_id"] = "\(user.id)"
           }
           
           
          let api = SimpleRequestApi()
           
           Utils.printDebug("\(parameters)")
           
           MyProgress.show()
           
                  api.run(url: OrderConstances.Api.API_GET_PAYMENT_URL, parameters: parameters) { (parser) in
                  
                      if(parser?.success == 1){
                       
                       MyProgress.dismiss()
                       
                          Utils.printDebug("\(parser)")
                       
                       
                   }else if(parser?.success == -1){
                       
                     
                      
                        MyProgress.dismiss()
                       
                   }
                      
                  }
           
          
           
       }
    
    
    
    

}


