//
//  CategoryCell.swift
//  NearbyStores
//
//  Created by Amine on 7/12/18.
//  Copyright © 2018 Amine. All rights reserved.
//

import UIKit
import SwiftIcons


protocol OrderCellDelegate:class  {
    //func successUtf8(data: String)
    func onPressed(id: Int)
    func onProductPressed(id: Int,module: String)
    func onPayNow(order: Order)
    func onOrderDetailPressed(order: Order)
}


class OrderCell: UICollectionViewCell, ProductLineDelegate, CustomButtonDelegate{
    

    
    func onProductPressed(id: Int,module: String) {
          
        if let del = delegate{
            del.onProductPressed(id: id, module: module)
        }
        
    }
    
    func onRemovePressed(index: Int) {
        
    }
    
    var controller: UIViewController?
    
    @IBOutlet weak var payment_status_badge: EdgeLabel!
    @IBOutlet weak var status_badge: EdgeLabel!
    @IBOutlet weak var order_label: UILabel!
    @IBOutlet weak var product_container: UIStackView!
    @IBOutlet weak var option: UIButton!
    
    var delegate: OrderCellDelegate?
    @IBAction func option_action(_ sender: Any) {
        if let o = order, let del = delegate{
            del.onPressed(id: o.id)
        }
    }
    
  
    func setupSettings() {
        
        order_label.isUserInteractionEnabled = true
        
        let gestureRecognizer1 = UITapGestureRecognizer(target: self, action: #selector(option_action))
        order_label.addGestureRecognizer(gestureRecognizer1)
        
        status_badge.isUserInteractionEnabled = true
        
        let gestureRecognizer2 = UITapGestureRecognizer(target: self, action: #selector(option_action))
        status_badge.addGestureRecognizer(gestureRecognizer2)
        

        order_label.initBolodFont()
        product_container.translatesAutoresizingMaskIntoConstraints = false
        product_container.distribution = .fillProportionally
        
        
        self.status_badge.layer.cornerRadius = self.status_badge.frame.height/3
        self.status_badge.layer.masksToBounds = true
        self.status_badge.backgroundColor = .orange
        self.status_badge.leftTextInset = 10
        self.status_badge.rightTextInset = 10
               //text color & font
        self.status_badge.textColor = .white
        self.status_badge.textAlignment = .center
        self.status_badge.initBolodFont(size: 13)
        self.status_badge.text = "Pending".localized
        
        
        
        self.payment_status_badge.layer.cornerRadius = self.status_badge.frame.height/3
        self.payment_status_badge.layer.masksToBounds = true
        self.payment_status_badge.backgroundColor = .orange
        self.payment_status_badge.leftTextInset = 10
        self.payment_status_badge.rightTextInset = 10
               //text color & font
        self.payment_status_badge.textColor = .white
        self.payment_status_badge.textAlignment = .center
        self.payment_status_badge.initBolodFont(size: 13)
        self.payment_status_badge.text = "Pending".localized
        self.payment_status_badge.isHidden = true
        
    }
    
    func collapse() {
        
        guard let o = order else {
           return
        }
        
        let arrow_down = UIImage.init(icon: .ionicons(.arrowDownB), size: CGSize(width: 24, height: 24), textColor: Colors.primaryColor)
              let arrow_up = UIImage.init(icon: .ionicons(.arrowUpB), size: CGSize(width: 24, height: 24), textColor: Colors.primaryColor)
              
        if o.is_open{
                  option.setImage(arrow_up, for: .normal)
              }else{
                  option.setImage(arrow_down, for: .normal)
        }
        
        UIView.animate(withDuration: 0.15) { () -> Void in
            
            if(o.is_open){
                self.product_container.isHidden = false
            }else{
                self.product_container.isHidden = true
            }
                   
        }
        
    }
    
    var order: Order?
    
    func setup(order: Order) {
     
        self.order = order
        
        order_label.text = "\("Order".localized) #\(order.id)"
       
        
        //order status
        let status = order.status.split(separator: ";")
        
        if(status.count > 0){
            let s:String  = String(status[0])
            let c:String  = String(status[1])
            status_badge.text = s
            status_badge.backgroundColor = Utils.hexStringToUIColor(hex: c)
        }else{
            status_badge.text = order.status
        }
        
        
        //payment status
        let payment_status = order.payment_status.split(separator: ";")
        
        if(payment_status.count > 0){
            let s:String  = String(payment_status[0])
            let c:String  = String(payment_status[1])
            payment_status_badge.text = s
            payment_status_badge.backgroundColor = Utils.hexStringToUIColor(hex: c)
            payment_status_badge.isHidden = false
        }else{
            payment_status_badge.text = order.payment_status
        }
    
        
        
        product_container.removeAllArrangedSubviews()
    
        var total = 0.0
        var total_currency: Currency? = nil
        
        
        Utils.printDebug(" ======== > \(order.items)")
        
        for item in order.items{
            
            var price = ""
            if let currency = item.currency {
                if let pprice = currency.parseCurrencyFormat(price: Float(item.amount * item.Qty)){
                    price = pprice
                    total_currency = currency
                }
            }
            
            
            
            let p = ProductLineItem(
                id: item.id,
                module: item.module,
                image_url: item.image,
                name: item.name,
                desc: "\("Qty".localized): \(item.Qty)" ,
                amount_s: price,
                amount_v: item.amount * item.Qty,
                qty: item.Qty,
                variants: []
            )
            
            
            total = ( item.amount * item.Qty ) + total
          
            
            let pl = ProductLine.newInstance().setup(product: p)
            let line_size = ( 70  +  (12 * getLineSize(variants: []) ) )
            pl.desc.text = pl.desc.text! + getLineDescription(variants: [])
            pl.heightAnchor.constraint(equalToConstant: CGFloat(line_size)).isActive = true
            
            
            product_container.addArrangedSubview(pl)
          
          
            pl.delegate = self
        }
        
        
        
        if let currency = total_currency {
            
            
            let extras = OrderParser.parse_extras(order: order)
            
            
            var extras_value = 0.0
            
            if extras.count > 0{
                for (key, value) in extras {
                    extras_value = value + extras_value
                }
            }
            
          
           
            
            if order.amount > 0 {
                
                if let pprice = currency.parseCurrencyFormat(price: Float(order.amount)){
                               
                    let am = AmoutView.newInstance().setup(amount: pprice)
                    am.heightAnchor.constraint(equalToConstant: 70).isActive = true
                    product_container.addArrangedSubview(am)
                    
                    if(order.amount > total && total > 0){
                       // am.display_sub_label(title: "Tax included.".localized)
                    }else{
                        am.hide_sub_label()
                    }
                    
                }
            }else if let pprice = currency.parseCurrencyFormat(price: Float(total)){
                               
                    let am = AmoutView.newInstance().setup(amount: pprice)
                    am.heightAnchor.constraint(equalToConstant: 70).isActive = true
                    product_container.addArrangedSubview(am)
                
                    am.hide_sub_label()
            }
            
        }
        
        
        if(order.invoice > 0){
            
            let paynow = CustomButtonView.newInstance().setup(title: "Pay Now".localized)
            paynow.heightAnchor.constraint(equalToConstant: 70).isActive = true
            paynow.delegate = self
            paynow.id = CB_PAY_NOW_BTN
            
            product_container.addArrangedSubview(paynow)
            
        }else{
            
            let order_detail = CustomButtonView.newInstance().setup(title: "Order Detail".localized)
            order_detail.heightAnchor.constraint(equalToConstant: 70).isActive = true
            order_detail.delegate = self
            order_detail.button.setCustomButtonControlStyle(active: false)
            
            order_detail.id = CB_ORDER_DETAIL_BTN
            product_container.addArrangedSubview(order_detail)
            
        }
        
       
        
        
        self.collapse()
    }
    
    let CB_PAY_NOW_BTN = 1
    let CB_ORDER_DETAIL_BTN = 2
    
    func onCBPressed(object: CustomButtonView) {
        if let del = delegate, let o = order, object.id == CB_PAY_NOW_BTN{
            del.onPayNow(order: o)
        }else if let del = delegate, let o = order, object.id == CB_ORDER_DETAIL_BTN{
            del.onOrderDetailPressed(order: o)
        }
    }
    
    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"
            }
           
        }
        
        return text
    }
  

}
