//
//  CartViewController.swift
//  Dealify
//
//  Created by Amine  on 1/31/21.
//  Copyright © 2021 Amine. All rights reserved.
//

import UIKit
import SwiftEventBus


class CartViewController: MyUIViewController, ProductLineDelegate, LoginControllerDelegate{
    
    
    func loginSuccess(controller: LoginViewController, user: User) {
        
    }
    
    func loginFaild(controller: LoginViewController) {
        
    }
    
    @IBOutlet weak var order_container: UIView!
    @IBOutlet weak var order_button: UIButton!
    @IBOutlet weak var total_label: UILabel!
    @IBOutlet weak var total_value: UILabel!
    @IBOutlet weak var bstackview: UIStackView!
    
    func startLoginVC() {
           
           let sb = UIStoryboard(name: "Login", bundle: nil)
           if sb.instantiateInitialViewController() != nil {
               let ms: LoginViewController = sb.instantiateViewController(withIdentifier: "loginVC") as! LoginViewController
               ms.delegate = self
               self.present(ms, animated: true)
           }
           
       }
    
    
    
    @IBAction func order_action(_ sender: Any) {
        
        guard let cart = Cart.find() else {
          return
        }
        
        if !Session.isLogged(){
            startLoginVC()
            return
        }
        
        let sb = UIStoryboard(name: "Order", bundle: nil)
        let ms: OrderViewController = sb.instantiateViewController(withIdentifier: "orderVC") as! OrderViewController
  
        ms.cart = cart
        ms.modalPresentationStyle = .fullScreen
        
        if let controller = self.parent_controller{
            self.dismiss(animated: true) {
                controller.present(ms, animated: true)
            }
        }
      
    }
    
    var parent_controller: UIViewController?
    
    
    @IBOutlet weak var stackView: UIStackView!
    @IBOutlet weak var scrollView: UIScrollView!
    
    
    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var navigationBarItem: UINavigationItem!
    
    
    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
        
        
        topBarTitle.text = "Cart".localized
        
        navigationBarItem.titleView = topBarTitle
        
    }
    
    
    @objc func onBackHandler() {
        self.dismiss(animated: true)
    }
    
    
    func onProductPressed(id: Int, module: String) {
        
    }
    
    func onRemovePressed(index: Int) {
        
        Cart.removeProduct(id: index)
        
        setup_views()
        
        SwiftEventBus.post("update_cart_badge")
        
    }
    

    override func viewDidLoad() {
    
        self.view.backgroundColor = Colors.bg_gray_100
        self.scrollView.backgroundColor = Colors.bg_gray_100
        
    
        setupNavBarTitles()
        
        //setup views
        setupNavBarButtons()
        
        //setup options
        setup_views()
        
    }
    
    
    func setup_views() {
        
    
        stackView.removeAllArrangedSubviews()
   
        guard let cart = Cart.find() else {
            setup_order_button()
           return
        }
        
        
        
        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
                       
                    }
                }
                     
            }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()
            )
            

            let pl = ProductLine.newInstance().setup(product: p)
            
            let line_size = ( 70  +  (20 * getLineSize(variants: item.variants.toArray()) ) )
            pl.heightAnchor.constraint(equalToConstant: CGFloat(line_size)).isActive = true
            pl.roundCorners(radius: 10)
            
            pl.desc.text = pl.desc.text! + getLineDescription(variants: item.variants.toArray())
           
            pl.delegate = self
            pl.index = item.id
            pl.removable = true
            
            stackView.addArrangedSubview(pl)

        }
        
        setup_order_button()
        
    }
    
    
    private func setup_order_button(){
        
        self.bstackview.roundCorners(corners: [.topLeft, .topRight], radius: 20)
        
        self.order_button.setTitleColor(.white, for: .normal)
        self.order_button.initBoldFont()
        self.order_button.setTitle("Checkout".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
        
    
        guard let cart = Cart.find() else {
           return
        }
        
        if cart.items.count == 0{
            self.order_button.backgroundColor = Colors.gray
            self.order_button.isEnabled = false
            self.total_value.text = "--"
            return
        }
       
        
        var total: Float = 0
        var currency: Currency? = nil
        
        
        for item in cart.items{
            
            total = total + ( Float(item.amount) * Float(item.qty) )
        
            if let c = item.item!.currency {
                currency = c
            }
            
        }
        
       
        self.order_container.isHidden = false
        
        
        if let c = currency{
            if let pprice = c.parseCurrencyFormat(price: total){
                self.total_value.text = "%@".localized.format(arguments: "\(pprice)")
            }
        }
        
        self.order_button.setCustomButtonStyleMain()
      
    }
    
    
    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
    }
    

}
