//
//  CategoryCell.swift
//  NearbyStores
//
//  Created by DT Team 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 onButtonsPressed(order: Order,ocid: Int)
}


class OrderCell: UICollectionViewCell, ProductLineDelegate, OCustomButtonDelegate{
   
    
    func onOCB_Pressed(ocid: Int) {
        if let del = delegate, let o = order{
            del.onButtonsPressed(order: o,ocid: ocid)
        }
    }
    
    func onProductPressed(id: Int,module: String) {
          
        if let del = delegate{
            del.onProductPressed(id: id, module: module)
        }
        
    }
    
    var controller: UIViewController?
    
    @IBOutlet weak var delivery_status: 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() {
        
        roundCorners(radius: 10)
        
        order_label.isUserInteractionEnabled = true
        
        let gestureRecognizer1 = UITapGestureRecognizer(target: self, action: #selector(option_action))
        order_label.addGestureRecognizer(gestureRecognizer1)
        
    

        order_label.initBolodFont()
        product_container.translatesAutoresizingMaskIntoConstraints = false
        product_container.distribution = .fillProportionally
        
        
        self.delivery_status.layer.cornerRadius = self.delivery_status.frame.height/3
        self.delivery_status.layer.masksToBounds = true
        self.delivery_status.backgroundColor = .orange
        self.delivery_status.leftTextInset = 10
        self.delivery_status.rightTextInset = 10
               //text color & font
        self.delivery_status.textColor = .white
        self.delivery_status.textAlignment = .center
        self.delivery_status.initBolodFont(size: 14)
        self.delivery_status.text = "Pending".localized
    
        
    }
    
    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 ") #\(order.id)"
       
        
        delivery_status.isHidden = false
        
         if(order.delivery_status == 0){
            delivery_status.text = "Pending".localized
            delivery_status.backgroundColor = .orange
         }else if(order.delivery_status == 1){
            
            delivery_status.text = "Ongoing".localized
            delivery_status.backgroundColor = .blue
            
         }else if(order.delivery_status == 2){
            
            delivery_status.text = "Picked Up".localized
            delivery_status.backgroundColor = .blue
            
         }else if(order.delivery_status == 3){
            
            delivery_status.text = "Delivered".localized
            delivery_status.backgroundColor = Colors.lightGreen
            
         }else if(order.delivery_status == 4){
           
            delivery_status.text = "Reported".localized
            delivery_status.backgroundColor = .red
            
         }else{
            
            delivery_status.isHidden = true
            
         }
     
      
        product_container.removeAllArrangedSubviews()
    
        var total = 0.0
        var total_currency: Currency? = nil
        
        
        
        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
            )
            
          
            total = ( item.amount * item.Qty ) + total
          
            let pl = ProductLine.newInstance().setup(product: p)
            product_container.addArrangedSubview(pl)
                   
            pl.heightAnchor.constraint(equalToConstant: 70).isActive = true
              
            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
                }
                
            }
            
            let taxes_value = (order.amount - total - extras_value )
            var roundedF = Float(String(format: "%.2f", taxes_value))
            
         /*
            if let tax_amount = currency.parseCurrencyFormat(price: Float( taxes_value )), roundedF! > 0{
                
                let taxes = AmoutView.newInstance().setup(key: "Taxes".localized, value: tax_amount)
                taxes.heightAnchor.constraint(equalToConstant: 30).isActive = true
                product_container.addArrangedSubview(taxes)
                
            }
            
            if extras.count > 0{
                for (key, value) in extras {
                    
                    if let pprice = currency.parseCurrencyFormat(price: Float(value)){
                        let am = AmoutView.newInstance().setup(key: key.localized, value: "\(pprice)")
                        am.heightAnchor.constraint(equalToConstant: 30).isActive = true
                        product_container.addArrangedSubview(am)
                    }
                  
                }
            }*/
            
          
            
            
            if order.amount > 0 {
                if let pprice = currency.parseCurrencyFormat(price: Float(order.amount)){
                               
                    let am = AmoutView.newInstance().setup(amount: pprice)
                    am.heightAnchor.constraint(equalToConstant: 30).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.delivery_status == OrderDeliveryStatus.DELIVERED){
                if let value = currency.parseCurrencyFormat(price: Float( order.delivery_commission )){
                    let deliveryValue = AmoutView.newInstance().setup(key: "You got".localized, value: "\(value)")
                    deliveryValue.heightAnchor.constraint(equalToConstant: 30).isActive = true
                    deliveryValue.amount_value.textColor = Colors.green
                    deliveryValue.amount_value.initBolodFont(size: 16)
                    product_container.addArrangedSubview(deliveryValue)
                }
            }else{
                if let value = currency.parseCurrencyFormat(price: Float( order.delivery_commission )){
                    let deliveryValue = AmoutView.newInstance().setup(key: "You get".localized, value: "+\(value)")
                    deliveryValue.heightAnchor.constraint(equalToConstant: 30).isActive = true
                    deliveryValue.amount_value.textColor = Colors.green
                    deliveryValue.amount_value.initBolodFont(size: 16)
                    product_container.addArrangedSubview(deliveryValue)
                }
            }
           
            
            
        }
        
        let b_c_stackView = UIStackView()
        b_c_stackView.axis = .horizontal
        b_c_stackView.alignment = .fill
        b_c_stackView.distribution = .fillEqually
        b_c_stackView.spacing = CGFloat(0)
        b_c_stackView.translatesAutoresizingMaskIntoConstraints = false
        b_c_stackView.backgroundColor = .red
        b_c_stackView.heightAnchor.constraint(equalToConstant: 70).isActive = true
              
        
        
        if(order.delivery_status == OrderDeliveryStatus.PENDING){
            
            let accept_btn = OCustomButtonView.newInstance();
            accept_btn.id = 1
            accept_btn.oc_button.initBoldFont()
            accept_btn.oc_button.setCustomButtonControlStyle(active: true)
            accept_btn.delegate = self
            accept_btn.oc_button.setTitle("Update".localized, for: .normal)
            
            b_c_stackView.addArrangedSubview(accept_btn)
            
            
            let contact_btn = OCustomButtonView.newInstance();
            contact_btn.id = 3
            contact_btn.oc_button.initBoldFont()
            contact_btn.oc_button.setTitle("Detail".localized, for: .normal)
            contact_btn.oc_button.setCustomButtonControlStyle(active: false)
            contact_btn.delegate = self
            
            b_c_stackView.addArrangedSubview(contact_btn)

            
        }else if(order.delivery_status == OrderDeliveryStatus.ONGOING
            || order.delivery_status == OrderDeliveryStatus.PICKED_UP
            || order.delivery_status == OrderDeliveryStatus.DELIVERED){
            
            
            let order_detail_btn = OCustomButtonView.newInstance();
            order_detail_btn.id = 2
            order_detail_btn.oc_button.initBoldFont()
            order_detail_btn.oc_button.setTitle("Order Detail".localized, for: .normal)
            order_detail_btn.oc_button.setCustomButtonControlStyle(active: false)
            order_detail_btn.delegate = self
            
            b_c_stackView.addArrangedSubview(order_detail_btn)
            
        }
        
    
        
       
        product_container.addArrangedSubview(b_c_stackView)
        
        self.collapse()
    }
  

}
