//
//  Products_HCards.swift
//  NearbyProducts
//
//  Created by Amine  on 8/11/19.
//  Copyright © 2019 Amine. All rights reserved.
//

import Foundation
import UIKit


protocol Products_HCards_Delegate {
    func onProductsLoaded(count: Int)
}

class Products_HCards: UIView ,UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, ProductLoaderDelegate{
    
    
    var delegate: Products_HCards_Delegate? = nil
    
    class func instanceFromNib(name: String) -> UIView {
        return UINib(nibName: name, bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
    }
    
    @IBOutlet weak var h_header: UIView!
    @IBOutlet weak var h_label: EdgeLabel!
    @IBOutlet weak var h_collection: UICollectionView!
    @IBOutlet weak var h_showAll: UIButton!
    
    
    @IBAction func showAllAction(_ sender: Any) {
           
        if let _ = self.style{
            
            showMore()
          
        }
         
           
    }
    
    func showMore() {
        
        let sb = UIStoryboard(name: "ResultList", bundle: nil)
        let ms: ResultListViewController = sb.instantiateViewController(withIdentifier: "resultlistVC") as! ResultListViewController
        
        
        ms.current_module = AppConfig.HomeStruct.Tags.TAG_PRODUCTS
        
      
        ms.config.backHome = true
        ms.config.customToolbar = true
                   
 
        var parameters = [
            "__req_search": __req_search,
            "__req_category": String(__req_category),
            "__req_redius": String(AppConfig.distanceMaxValue),
            "__req_opening_time": "0",
        ]
        
        if let _style = style, _style.type == CardHorizontalViewTypes.Recent_Products{
            
            ms.config.custom_title =  _style.Title?.localized
            ms.request = ListProductView.Request.recent
            parameters["__req_list_order"] = ListProductView.Request.recent
             
        }else if let _style = style, _style.type == CardHorizontalViewTypes.FeaturedProducts{
            
            ms.config.custom_title = _style.Title?.localized
            ms.request = ListProductView.Request.featured
            parameters["__req_list_order"] = ListProductView.Request.featured
            parameters["__req_is_featured"] = String(1)
            
        }else if let _style = style, _style.type == CardHorizontalViewTypes.TopSellerProducts{
            
            ms.config.custom_title = _style.Title?.localized
            ms.request = ListProductView.Request.top_seller
            parameters["__req_list_order"] = ListProductView.Request.top_seller
            parameters["__req_is_featured"] = "-1"
            
        }
        
        ms.parameters = parameters
        
        if let controller = self.viewController{
            
            controller.present(ms, animated: true)
            
        }else if let controller = self.viewNavigationController{
            
            controller.pushViewController(ms, animated: true)
            
        }else if let controller = self.viewTabBarController{
            
            controller.navigationController?.pushViewController(ms, animated: true)
        }
    }
    
    
    var style: CardHorizontalStyle?
    
    var viewController: UIViewController? = nil
    var viewNavigationController: UINavigationController? = nil
    var viewTabBarController: UITabBarController? = nil
    
    
    static func newInstance(style: CardHorizontalStyle) -> UIView{
        
        //load xib
        let mProducts_HCards = instanceFromNib(name: "Products_HCards") as! Products_HCards
        
        mProducts_HCards.style = style
        mProducts_HCards.setup()
        
        return mProducts_HCards
        
    }
    
    
    enum Request {
        static let nearby = 0
        static let saved = -1
        static let recent = 1
    }
    
    //request
    var __req_loc_latitude: Double = 0.0
    var __req_loc_longitude: Double = 0.0
    var __req_list_order: String = ""
    var __req_category: Int = 0
    var __req_redius: Int  = AppConfig.distanceMaxValue
    var __req_list: Int = Request.nearby
    var __req_search: String = ""
    var __req_page: Int = 1
    var __req_store: Int = 0
    var __req_parent_id: Int = 0
    var __req_current_date: String = ""
    var __req_default_tz: String = ""
    var __req_opening_time: Int = 0
    
    //RESULT
    var GLOBAL_COUNT: Int = 0
    var LIST: [Product] = [Product]()
    
    
    let padding_size = CGFloat(20)
    
    
    func setup(){
        
        self.backgroundColor = .clear
        
        self.h_label.leftTextInset = padding_size
        self.h_label.rightTextInset = padding_size
        self.h_label.initBolodFont(size: 18)
        
        
        self.h_showAll.initItalicFont()
        self.h_showAll.setTitleColor(.black, for: .normal)
        self.h_showAll.contentEdgeInsets = UIEdgeInsets(top: 0, left: padding_size, bottom: 0, right: padding_size)
        self.h_showAll.setupShowMore()
               
        
        if let flowLayout = h_collection.collectionViewLayout as? UICollectionViewFlowLayout {
            flowLayout.scrollDirection = .horizontal
            flowLayout.minimumLineSpacing = 0
            layoutIfNeeded()
        }
        
        
        h_collection.contentInset = UIEdgeInsets(top: padding_size, left: padding_size, bottom: padding_size, right: padding_size)
        
         
        h_collection.dataSource = self
        h_collection.delegate = self
        h_collection.showsHorizontalScrollIndicator = false
        
        h_collection.backgroundColor = .clear
        h_collection.register(UINib(nibName: "ProductCardCell", bundle: nil), forCellWithReuseIdentifier: "productCardCellId")
        
        h_collection.isScrollEnabled = true
        
        h_showAll.isHidden = true
        
        
    }
    
    func test() {
        
        let product = Product()
        self.LIST.append(product)
        self.LIST.append(product)
        self.LIST.append(product)
        self.LIST.append(product)
        self.LIST.append(product)
        self.LIST.append(product)
        self.LIST.append(product)
        self.LIST.append(product)
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
        
        let cell: ProductCardCell  = collectionView.dequeueReusableCell(withReuseIdentifier: "productCardCellId", for: indexPath) as! ProductCardCell
        
        let object = LIST[indexPath.row]
        
        cell.setting(style: style!)
        
        if object.id > 0{
             cell.setup(object: object)
        }else{
             cell.setup(object: nil)
        }
       
        return cell
        
    }
    
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let product = self.LIST[indexPath.row]
        product.save()
        
        
        let sb = UIStoryboard(name: "ProductDetail", bundle: nil)
        if sb.instantiateInitialViewController() != nil {

        let ms: ProductDetailViewController = sb.instantiateViewController(withIdentifier: "productdetailVC") as! ProductDetailViewController

        ms.product_id = product.id

        if let controller = self.viewController{
                                  controller.present(ms, animated: true)
        }else if let controller = self.viewNavigationController{
                                  controller.pushViewController(ms, animated: true)
        }else if let controller = self.viewTabBarController{
                                  controller.navigationController!.pushViewController(ms, animated: true)
            }
        }
        
    }
    
   
    
    static let header_size = Float(50)
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        if let style = self.style, let height = style.height, let width = style.width{
            //add 60 for store information
            
            let calculated_height = height-Products_HCards.header_size
            
            let ratio = Float(height/calculated_height)
            let calculated_width = Float(width/ratio)
            
            return CGSize(width: CGFloat(calculated_width-50),height: CGFloat(calculated_height))
        }else{
            return CGSize(width: CGFloat(60) , height: CGFloat(60))
        }
        
        
    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return LIST.count
    }
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return CGFloat(padding_size)
    }
    
    //API
    
    var productLoader: ProductLoader = ProductLoader()
    
    func load () {
        
        make_as_loader()
        
        self.productLoader.delegate = self
        
        //Get current Location
        
        var parameters = [
            "limit"          : "6"
        ]
      
       if __req_redius > 0 && __req_redius < 100 {
           parameters["radius"] = String( (__req_redius*1000) ) //radius by merters
       }
       

       parameters["category_id"] = String(__req_category)
       parameters["page"] = String(__req_page)
       parameters["search"] = String(__req_search)
       parameters["date"] = String(__req_search)
       parameters["store_id"] = String(__req_store)
        
        
        if(style?.type == CardHorizontalViewTypes.FeaturedProducts){
            parameters["order_by"] = ListProductView.Request.nearby
            parameters["is_featured"] = String(1)
        }else if(style?.type == CardHorizontalViewTypes.Recent_Products){
            parameters["order_by"] = ListProductView.Request.recent
            parameters["is_featured"] = String(0)
        }else if(style?.type == CardHorizontalViewTypes.Nearby_Stores){
            parameters["order_by"] = ListProductView.Request.nearby
            parameters["is_featured"] = String(0)
        }else if(style?.type == CardHorizontalViewTypes.TopSellerProducts){
            parameters["order_by"] = ListProductView.Request.top_seller
        }else{
            parameters["order_by"] = String(__req_list_order)
        }
                        
                              
        if(__req_loc_latitude != 0.0 && __req_loc_longitude != 0.0){
            parameters["latitude"] = String(__req_loc_latitude)
            parameters["longitude"] = String(__req_loc_longitude)
        }else  if let guest = Guest.getInstance() {
            parameters["latitude"] = String(guest.lat)
            parameters["longitude"] = String(guest.lng)
        }
        
        if __req_parent_id > 0 {
            parameters["parent_id"] = String(__req_parent_id)
        }
        
        Utils.printDebug("\(parameters)")
 
        self.productLoader.load(url: Constances.Api.API_GET_PRODUCTS,parameters: parameters)
        
    }
    
    
    func success(parser: ProductParser,response: String) {
        
        make_as_result()
    
        if parser.success == 1 {
            
            
            let products = parser.parse()
            
            
            self.GLOBAL_COUNT = parser.count
            
            if(GLOBAL_COUNT>6){
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                    let animation = UIAnimation(view: self.h_showAll)
                    animation.zoomIn()
                }
            }
            
            if products.count > 0 {
                
                Utils.printDebug("We loaded \(products.count)")
                
                
                if self.__req_page == 1 {
                    self.LIST = products
                }else{
                    self.LIST += products
                }
                
                self.h_collection.reloadData()
                
                if self.LIST.count < self.GLOBAL_COUNT {
                    self.__req_page += 1
                }
                
                
            }else{
                
                self.isHidden = true
                
            }
            
            
            if let del = delegate{
                delegate?.onProductsLoaded(count: self.LIST.count)
            }

            
        }else {
            
            if let errors = parser.errors {
                
                Utils.printDebug("===> Request Error with Messages! ListProducts")
                Utils.printDebug("\(errors)")
                
                
            }
            
            if let del = delegate{
                delegate?.onProductsLoaded(count: 0)
            }
            
        }
        
    }
    
    func emptyAndReload()  {
        
        self.LIST = []
        self.GLOBAL_COUNT = 0
        self.h_collection.reloadData()
        
    }
    
    func error(error: Error?,response: String) {
        
        if let del = delegate{
            delegate?.onProductsLoaded(count: 0)
        }
        
        Utils.printDebug("===> Request Error! ListProducts")
        Utils.printDebug("\(response)")
        
    }
    
    
    
}

extension Products_HCards{
    
    func make_as_loader(){
        
        self.LIST = []
        
        let object = Product()
        for _ in 0...5{
            self.LIST.append(object)
        }
        
        self.h_collection.reloadData()
        self.h_collection.isScrollEnabled = false
        
    }
    
    func make_as_result() {
        
        self.LIST = []
        self.h_collection.reloadData()
        self.h_collection.isScrollEnabled = true
    }
    
}

extension UIButton{
    func setupShowMore() {
        self.initItalicFont()
        self.setIcon(prefixText: "\("Show all".localized) ", prefixTextColor: .red, icon: .googleMaterialDesign(.arrowForward), iconColor: Colors.primaryColor, postfixText: "", postfixTextColor: .black, forState: .normal, textSize: 15, iconSize: 12)
    }
}
