//
//  MessengerViewController.swift
//  NearbyStores
//
//  Created by Amine on 6/14/18.
//  Copyright © 2018 Amine. All rights reserved.
//

import UIKit
import SwiftEventBus
import AssistantKit
import RealmSwift



class VariantSelectorController: MyUIViewController, V_Group_Update_Delegate, QtySelectorDelegate{

    
    
    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var navigationBarItem: UINavigationItem!
    @IBOutlet weak var viewContainer: UIView!
    @IBOutlet weak var group_container: UIStackView!
    
    
    
    var item_id: Int? = nil
    var result: [V_GroupResult] = []
    
    func setupNavBarButtons() {
        
        let color = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.primaryColor)
        
        //arrow back icon
        var arrowImage: UIImage? = nil
        if Utils.isRTL(){
            arrowImage = UIImage.init(icon: .ionicons(.iosArrowForward), size: CGSize(width: 30, height: 30), textColor: color)
        }else{
            arrowImage = UIImage.init(icon: .ionicons(.iosArrowBack), size: CGSize(width: 30, height: 30), textColor: color)
        }
        
        
        let customBarButtonItem = UIBarButtonItem(image: arrowImage!, style: .plain, target: self, action: #selector(onBackHandler))
        customBarButtonItem.setIcon(icon: .ionicons(.iosArrowBack), iconSize: 25, color: color)
        
        
        navigationBarItem.leftBarButtonItems = []
        navigationBarItem.rightBarButtonItems = []
        navigationBarItem.leftBarButtonItems?.append(customBarButtonItem)
        
    }
    
    
    
    
    let topBarTitle: EdgeLabel = {
        
        let titleLabel = EdgeLabel()
        
        titleLabel.text = ""
        titleLabel.textColor =  AppDesignUtils.defaultModeColor(dark: .white, light: Colors.primaryColor)
        titleLabel.font = UIFont.systemFont(ofSize: 20)
        
        return titleLabel
        
    }()
    
    func setupNavBarTitles() {
        
        
        let rect = CGRect(x: 0, y: 0, width: view.frame.width - 32, height: view.frame.height)
        topBarTitle.frame = rect
        topBarTitle.textColor = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.primaryColor)
        topBarTitle.font = UIFont(name: AppConfig.Design.Fonts.regular, size: 17)
        topBarTitle.leftTextInset = 5
        
        
        guard let id = item_id, let product = Product.findById(id: id) else {
            return
        }
        
        topBarTitle.text = product.name
        
        navigationBarItem.titleView = topBarTitle
        
    }
    
    @objc func onBackHandler() {
        self.dismiss(animated: true)
    }
    
   
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNavBarTitles()
        
        //setup views
        setupNavBarButtons()
        
        //setup options
        setup()
      
    }
    
    
    func setup()  {
        
        guard let id = item_id, let product = Product.findById(id: id) else {
            return
        }
          
        setup_group(product: product)
        
        setup_order_button(product: product)
        
    }
    
    func setup_group(product: Product) {
        
        for group in product.variants {
            let grp = V_Group.newInstance(group: group)
            grp.delagate = self
            group_container.addArrangedSubview(grp)
        }
        
    }
    
    func onUpdated(group: VariantGroup) {
        
        self.result = []
        //uncheck_all
        for subview in self.group_container.subviews{
            
            if subview is V_Group{
               
                let grp_view = subview as! V_Group
            
                let result = getResult(grp_view: grp_view)
                self.result.append(result)
               
            }
            
        }
        
        
        guard let id = item_id, let product = Product.findById(id: id) else {
            return
        }
       
        var final_amount: Double = Double(product.product_value)
        
        for r in self.result{
            final_amount = final_amount + r.calculated
        }
        
        
        if product.product_type == "price" {
                   
            if let currency = product.currency {
                
                if let pprice = currency.parseCurrencyFormat(price: Float(final_amount) ){
                    self.total_value.text = pprice
                }
               
            }
                   
        }
        
       
    }
    
    func getResult(grp_view: V_Group) ->  V_GroupResult{
        
        var result = V_GroupResult()
        result.grp_id = grp_view.group!.group_id
        result.calculated = 0
        result.grp_label = grp_view.group!.group_label
        result.options =  List<VariantOption>()
        
        //uncheck_all
        for subview in grp_view.option_container.subviews{
            
            if subview is V_Option{
               
                let opt_view = subview as! V_Option
                if(opt_view.is_checked){
                    
                    guard  let opt = opt_view.option else {
                        continue
                    }
                   
                    result.options.append(opt)
                    
                    if(opt.value > 0){
                        result.calculated =  result.calculated + opt.value
                    }
                   
                }
               
            }
            
        }
        
        return result
        
    }
    
    
    @IBOutlet weak var order_container: UIView!
    @IBOutlet weak var order_button: UIButton!
    @IBOutlet weak var total_label: UILabel!
    @IBOutlet weak var total_value: UILabel!
    
    
    @IBAction func order_action(_ sender: Any) {
        
        guard let id = item_id, let product = Product.findById(id: id) else {
            return
        }
        
       
        var final_amount: Double = Double(product.product_value)
        
        for r in self.result{
            final_amount = final_amount + r.calculated
        }
        
    
        if product.stock >= 1 || product.stock == -1{
            
            let view = qtySelector.show(item: product, amount: Double(final_amount))
            
            view.cancel_btn.setTitle("Add to cart", for: .normal)
            view.confirm_btn.setTitle("Checkout".localized, for: .normal)
            
            qtySelector.delegate = self
            
        }else{
            
            var order_product = OrderProduct()
            order_product.item = product
            order_product.amount = final_amount
            order_product.qty = 1
            order_product.variants = result.toRealmList()
            
            self.startOrderController(product: order_product)
        }
    }
    
    
   
    
    func onQtySelectorRightPressed(qty: Double) {
        
    
        guard let id = item_id, let product = Product.findById(id: id) else {
            return
        }
        
    
       
        var final_amount: Double = Double(product.product_value)
        
        for r in self.result{
            final_amount = final_amount + r.calculated
        }
        
        var order_product = OrderProduct()
        order_product.item = product
        order_product.amount = final_amount
        order_product.qty = Int(qty)
        order_product.variants = result.toRealmList()
        
        self.startOrderController(product: order_product)
        
     }
     
     func onQtySelectorLeftPressed(qty: Double) {
        
    
        guard let id = item_id, let product = Product.findById(id: id) else {
            return
        }
        
       
         
       
        var final_amount: Double = Double(product.product_value)
        
        for r in self.result{
            final_amount = final_amount + r.calculated
        }
        
        let order_product = OrderProduct()
        order_product.item = product
        order_product.amount = final_amount
        order_product.qty = Int(qty)
        order_product.variants = result.toRealmList()
        
        
        
        if !Cart.hasStore(item0: order_product){
            self.showAlertError(title: "Cart".localized, content: ["err":"couldn't add an item from the different store".localized], msgBnt: "OK".localized)
            return
        }
        
        let cart = Cart.openCart(items: [order_product])
        cart.save()
        
        
        if let controller = self.parent_controller{
            self.dismiss(animated: true) {
                SwiftEventBus.post("update_cart_badge")
                controller.dismiss(animated: true)
            }
        }
        
     }
    
    
    private func setup_order_button(product: Product){
        
        guard product.order_enabled == 1 else{
            order_container.isHidden = true
            return
        }
       
       
        self.order_container.isHidden = false
        
        self.order_button.setTitleColor(.white, for: .normal)
        self.order_button.initBoldFont()
        self.order_button.setTitle("Continue".localized, for: .normal)
       
  
        self.total_label.textColor = .black
        self.total_label.initBolodFont(size: 14)
        
        self.total_value.textColor = Colors.primaryColor
        self.total_value.initBolodFont(size: 18)
        
        
        self.total_label.text = "Total".localized
        
        if let currency = product.currency {
            if let pprice = currency.parseCurrencyFormat(price: Float(product.product_value)){
                self.total_value.text = "%@".localized.format(arguments: "\(pprice)")
            }
        }
        
        self.order_button.setCustomButtonStyleMain()
      
    }
    
    lazy var qtySelector: QtySelectorView = {
          let launcher = QtySelectorView()
         // launcher.mainController = self
          return launcher
      }()
    
    func startOrderController(product: OrderProduct) {
           
        /*let sb = UIStoryboard(name: "Order", bundle: nil)
        let ms: OrderViewController = sb.instantiateViewController(withIdentifier: "orderVC") as! OrderViewController
        
       // Cart.removeAllProducts()
        
        let cart = Cart.openCart(items: [product])
        cart.save()
      
        ms.cart = cart
        
        if let controller = self.parent_controller{
            self.dismiss(animated: true) {
                controller.present(ms, animated: true)
            }
        }*/
        
        self.startCartController(product: product)
           
    }
    
    
    
    func startCartController(product: OrderProduct) {
        
        

        Cart.openCart(items: [product])
        
        
        
        let sb = UIStoryboard(name: "CartView", bundle: nil)
         let ms: CartViewController = sb.instantiateViewController(withIdentifier: "cart_vc") as! CartViewController
        ms.modalPresentationStyle = .fullScreen
        ms.parent_controller = self
        self.present(ms, animated: true)
    
    }
    
    var parent_controller: UIViewController?
    
}






