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

import UIKit
import SwiftEventBus
import SwiftIcons


protocol ResultListViewControllerDelegate {
    func onSearchButtonPressed(controller: ResultListViewController, type: String, view: UIView, search_dialog_controller: SearchDialogViewController)
    func onSearchResultBackPressed(controller: ResultListViewController, filterCache: SearchDialogViewController.FilterCache)
}

class ResultListViewController: MyUIViewController, SearchDialogViewControllerDelegate, FilterCheckBoxDelegate{
    
 
    
    
    let modules = [AppConfig.HomeStruct.Tags.TAG_STORES, AppConfig.HomeStruct.Tags.TAG_PRODUCTS]
    var current_module = AppConfig.HomeStruct.Tags.TAG_STORES
    
    var delegate: ResultListViewControllerDelegate? = nil
    var filterCache: SearchDialogViewController.FilterCache? = nil
    

  
    static var isAppear = false
    
    
    
    //Declare User For Current Session
    var myUserSession: User? = nil
    var viewManager: LoaderViewManager =  LoaderViewManager()
    var request: String = ListStoresView.Request.nearby

    
    var parameters: [String: String] = [
        "__req_category": "0",
        "__req_redius": String(AppConfig.distanceMaxValue),
        "__req_list_order": String(ListStoresView.Request.nearby),
        "__req_search": "",
        "__req_store": "0",
        "__req_page": "1",
        "__req_current_date": "",
        "__req_default_tz": "",
        "__req_is_featured": "",
    ]

    var category_id: Int? = nil

    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var navigationBarItem: UINavigationItem!
    @IBOutlet weak var viewContainer: UIView!
    @IBOutlet weak var topBarView: UIView!
    
    func renderResult(title: String) {
        
        topBarTitle.text = title
        
        instanceCurrentView()
        
        setNavBarButtons()
        
    
    }
    
    var listStyleBarButtonItem: UIBarButtonItem?
    var searchBarButtonItem: UIBarButtonItem?
    
    func setNavBarButtons() {
        
        let _color = 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)
        
        //setp search icon btn
        let searchImage = UIImage.init(icon: .linearIcons(.magnifier), size: CGSize(width: 25, height: 25), textColor: _color)
        
        searchBarButtonItem = UIBarButtonItem(image: searchImage, style: .plain, target: self, action: #selector(handleSearch))
        searchBarButtonItem!.tintColor = _color
        
        
        navigationBarItem.leftBarButtonItems = []
        navigationBarItem.rightBarButtonItems = []
        navigationBarItem.leftBarButtonItems?.append(customBarButtonItem)
        
        
        if(self.current_module != AppConfig.HomeStruct.Tags.TAG_STORES ){
            
            var font_icon: FontType?
            
            if req_list_style {
                font_icon = .dripicon(.viewThumb)
            }else{
                font_icon = .dripicon(.viewListLarge)
            }
            
            listStyleBarButtonItem = UIBarButtonItem(image:
                                                        UIImage.init(icon: font_icon!, size: CGSize(width: 25, height: 25), textColor: _color)
                , style: .plain, target: self, action: #selector(handleListStyle))
            
            listStyleBarButtonItem!.tintColor = _color

            
            navigationBarItem.rightBarButtonItems?.append(listStyleBarButtonItem!)
            
        }
       
        
        navigationBarItem.rightBarButtonItems?.append(searchBarButtonItem!)
       
        
    }
    
    var req_list_style = false
    
    @objc func handleListStyle(){
        
        if req_list_style{
            //change to grid
            req_list_style = false
            
            if let v = current_View{
                v.onListStyleChanged(style: .Grid)
            }
            
            setNavBarButtons()

            
        }else{
            //change to list
            req_list_style = true
            
            if let v = current_View{
                v.onListStyleChanged(style: .List)
            }
            
            setNavBarButtons()
            
    
        }
        
    }
    
    
    @objc func handleSearch() {
        
        Utils.printDebug("handleSearch: \(self.parameters)")
        
        let sb = UIStoryboard(name: "SearchDialog", bundle: nil)
        
        if let vc = sb.instantiateInitialViewController() {
            
            let searchDialog: SearchDialogViewController = vc as! SearchDialogViewController

            if let cache = filterCache, let _type = cache._type, let _view =  cache._view{
                searchDialog.setup(type: _type, view: _view)
            }else{
                
                Utils.printDebug("handleSearch: current_module =>\(self.current_module)")
                
                //instance current filter
                if(self.current_module == AppConfig.HomeStruct.Tags.TAG_STORES ){
                    
                    let mStoreSearch = UIView.loadFromNib(name: "StoreSearch") as! StoreSearch
                    mStoreSearch.ex_parameters = parameters
                    searchDialog.setup(type: AppConfig.HomeStruct.Tags.TAG_STORES, view: mStoreSearch)
                    
                }else if(self.current_module == AppConfig.HomeStruct.Tags.TAG_PRODUCTS ){
                    
                    let mProductSearch = UIView.loadFromNib(name: "ProductSearch") as! ProductSearch
                    mProductSearch.ex_parameters = parameters
                    searchDialog.setup(type: AppConfig.HomeStruct.Tags.TAG_PRODUCTS, view: mProductSearch)
                    
                }
                
            }

            searchDialog.delegate = self

            if let controller = self.tabBarController{
                controller.present(searchDialog, animated: true, completion: nil)
            }else{
                self.present(searchDialog, animated: true, completion: nil)
            }
            
        }
        
    }
    
    func getParameters(type: String, instance: UIView?) ->  [String: String] {
    
        parameters["__req_list_order"] = String(request)
    
        if type == AppConfig.HomeStruct.Tags.TAG_STORES{
            
            let myView = instance as! StoreSearch
            
            parameters = myView.ex_parameters
            
            parameters["__req_search"] = myView.search_field.text!
            parameters["__req_redius"] = String(Int(myView.sliderView.value))
           
            
        }else if type == AppConfig.HomeStruct.Tags.TAG_PRODUCTS{
            
            
            let myView = instance as! ProductSearch
            
            parameters = myView.ex_parameters
            
    
            parameters["__req_search"] = myView.search_field.text!
            parameters["__req_redius"] = String(Int(myView.sliderView.value))
          
            
        }
        
        
        Utils.printDebug("handleSearch: current_module =>\(parameters)")
    
        return parameters
    
    }
    
    func onSearch(type: String, view: UIView, controller: SearchDialogViewController) {
        
        controller.onBackHandler()
        
        filterCache = SearchDialogViewController.FilterCache()
        filterCache?._type = type
        filterCache?._view = view
        
        current_module = type

        
        self.parameters = getParameters(type: current_module, instance: view)
        
        Utils.printDebug("Result Parameters=> \(parameters)")
       
    
        if type == AppConfig.HomeStruct.Tags.TAG_STORES{
                
                  //Sort parameters DATE - GEO
                  if(SearchDialogViewController.selected_sort_type == SearchDialogViewController.SORT_RADIOBOW_KEY_GEO
                      && SearchDialogViewController.listing_custom_location_enabled){
                      
                      request = ListStoresView.Request.nearby
                      parameters["__req_order"] = String(ListStoresView.Request.nearby)
                      parameters["__req_loc_latitude"] = "\(SearchDialogViewController.listing_custom_location_latitude)"
                      parameters["__req_loc_longitude"] = "\(SearchDialogViewController.listing_custom_location_longitude)"
                      
                  }else  if(SearchDialogViewController.selected_sort_type == SearchDialogViewController.SORT_RADIOBOW_KEY_GEO){
                    
                    request = ListStoresView.Request.nearby
                    parameters["__req_order"] = String(ListStoresView.Request.nearby)
                    
                  }else{
                     
                      request = ListStoresView.Request.recent
                      parameters["__req_order"] = String(ListStoresView.Request.recent)
                     
                  }
               
                
              }else if type == AppConfig.HomeStruct.Tags.TAG_PRODUCTS{
                  
                  //Sort parameters DATE - GEO
                  if(SearchDialogViewController.selected_sort_type == SearchDialogViewController.SORT_RADIOBOW_KEY_GEO
                                 && SearchDialogViewController.listing_custom_location_enabled){
                                 
                      request = ListProductView.Request.nearby
                      parameters["__req_order"] = String(ListProductView.Request.nearby)
                      parameters["__req_loc_latitude"] = "\(SearchDialogViewController.listing_custom_location_latitude)"
                      parameters["__req_loc_longitude"] = "\(SearchDialogViewController.listing_custom_location_longitude)"
                                 
                  }else if(SearchDialogViewController.selected_sort_type == SearchDialogViewController.SORT_RADIOBOW_KEY_GEO){
                                 
                      request = ListProductView.Request.nearby
                      parameters["__req_order"] = String(ListProductView.Request.nearby)
                                
                  }else{
                                
                      request = ListProductView.Request.recent
                      parameters["__req_order"] = String(ListProductView.Request.recent)
                                
                  }
                
              }else if type == AppConfig.HomeStruct.Tags.TAG_OFFERS{
                
                //Sort parameters DATE - GEO
                if(SearchDialogViewController.selected_sort_type == SearchDialogViewController.SORT_RADIOBOW_KEY_GEO
                               && SearchDialogViewController.listing_custom_location_enabled){
                               
                    request = ListOfferView.Request.nearby
                    parameters["__req_order"] = String(ListProductView.Request.nearby)
                    parameters["__req_loc_latitude"] = "\(SearchDialogViewController.listing_custom_location_latitude)"
                    parameters["__req_loc_longitude"] = "\(SearchDialogViewController.listing_custom_location_longitude)"
                               
                }else if(SearchDialogViewController.selected_sort_type == SearchDialogViewController.SORT_RADIOBOW_KEY_GEO){
                               
                    request = ListOfferView.Request.nearby
                    parameters["__req_order"] = String(ListProductView.Request.nearby)
                              
                }else{
                              
                    request = ListOfferView.Request.recent
                    parameters["__req_order"] = String(ListProductView.Request.recent)
                              
                }
              
            }
        
       
      
        renderResult(title: "Result for %@ ".localized.format(arguments: current_module.localized))
        
        
        setupTopBarView()
        
    }
    
    
    @objc func onBackHandler()  {
        
        if let del = delegate, let cache = filterCache{
            del.onSearchResultBackPressed(controller: self, filterCache: cache)
        }
        
        if let controller = self.navigationController{
            controller.popViewController(animated: true)
        }else{
            self.dismiss(animated: true)
        }
        
    }
    
    

    override func viewDidLoad() {
        super.viewDidLoad()

      
        if let session = Session.getInstance(), let user = session.user {
            myUserSession = user
        }
        
        self.view.backgroundColor = Colors.darkColor
        
        self.navigationBar.isTranslucent = false
        self.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        self.navigationBar.shadowImage = UIImage()
        self.navigationBar.tintColor = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.primaryColor)
        
    
        setupNavBarTitles()
        //setup views
        setNavBarButtons()

        
         if let custom_title = config.custom_title{
            renderResult(title: custom_title)
        }else{
            renderResult(title: "Result for %@ ".localized.format(arguments: current_module.localized))
        }
        
    
        //setup top bar for first time
        setupTopBarView()
    
        
    }
    
    
    let topBarTitle: EdgeLabel = {
        
        let titleLabel = EdgeLabel()
        
        titleLabel.text = ""
        titleLabel.textColor = 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 = Colors.primaryColor
        topBarTitle.font = UIFont(name: AppConfig.Design.Fonts.regular, size: 17)
        topBarTitle.leftTextInset = 5
        
       
    
        if let custom_title = config.custom_title{
            topBarTitle.text = custom_title
        }else{
            topBarTitle.text = ""
        }
       
        
        navigationBarItem.titleView = topBarTitle
        
    }
    
    
    
    
    var current_View: BaseView? = nil
    
    func instanceCurrentView(){

         parameters["__req_list_order"] = String(self.request)
        
      
        if current_module == AppConfig.HomeStruct.Tags.TAG_STORES {
            
            let cell: ListStoresView  = ListStoresView()
            cell.frame = viewContainer.bounds
            viewContainer.addSubview(cell)
            view.addConstraintsWithFormat(format: "H:|[v0]|", views: cell)
            view.addConstraintsWithFormat(format: "V:|[v0]|", views: cell)
        
            cell.viewController = self
           
            if let cat = self.category_id{
                cell.__req_category = cat
            }
            
            cell.__req_category = Int(parameters["__req_category"]!)!
            cell.__req_search =  parameters["__req_search"]!
            cell.__req_redius = Int(parameters["__req_redius"]!)!
           
            if let lat = parameters["__req_loc_latitude"], let lng = parameters["__req_loc_longitude"]{
                cell.__req_lat = Double(lat)!
                cell.__req_lng = Double(lng)!
            }
            
            cell.extra_parameters = parameters
            
            cell.setupViews()
            cell.fetch(request: BaseView.Request.defaultRequest)
            
            current_View = cell
         
        }else if current_module == AppConfig.HomeStruct.Tags.TAG_PRODUCTS {
        
            let cell: ListProductView  = ListProductView()
            
            //cell.filter_enabled = false
            
            cell.frame = viewContainer.bounds
            viewContainer.addSubview(cell)
            view.addConstraintsWithFormat(format: "H:|[v0]|", views: cell)
            view.addConstraintsWithFormat(format: "V:|[v0]|", views: cell)
            
            cell.viewController = self
            
         
            if let cat = self.category_id{
                cell.__req_category = cat
            }
            
            if let __req_is_featured = parameters["__req_is_featured"], let id = Int(__req_is_featured){
                cell.__req_is_featured = id
            }
             
            if let __req_store = parameters["__req_store"]{
                cell.__req_store = Int(__req_store)!
            }
            
            cell.__req_redius = Int(parameters["__req_redius"]!)!
            cell.__req_search = parameters["__req_search"]!
            cell.__req_category = Int(parameters["__req_category"]!)!
           
          
             if let lat = parameters["__req_loc_latitude"], let lng = parameters["__req_loc_longitude"]{
                cell.__req_lat = Double(lat)!
                cell.__req_lng = Double(lng)!
            }
            
            cell.extra_parameters = parameters
            
            cell.setupViews()
            cell.fetch(request: ListStoresView.Request.nearby)
            
            
            current_View = cell
            
        
           
        }else if current_module == AppConfig.HomeStruct.Tags.TAG_OFFERS {
            
            let cell: ListOfferView  = ListOfferView()
            
            //cell.filter_enabled = false
            
            cell.frame = viewContainer.bounds
            viewContainer.addSubview(cell)
            view.addConstraintsWithFormat(format: "H:|[v0]|", views: cell)
            view.addConstraintsWithFormat(format: "V:|[v0]|", views: cell)
            
            cell.viewController = self
            
         
            if let cat = self.category_id{
                cell.__req_category = cat
            }
            
             
            if let __req_store = parameters["__req_store"]{
                cell.__req_store = Int(__req_store)!
            }
            
            cell.__req_redius = Int(parameters["__req_redius"]!)!
            cell.__req_search = parameters["__req_search"]!
            cell.__req_category = Int(parameters["__req_category"]!)!
           
          
             if let lat = parameters["__req_loc_latitude"], let lng = parameters["__req_loc_longitude"]{
                cell.__req_lat = Double(lat)!
                cell.__req_lng = Double(lng)!
            }
            
            cell.extra_parameters = parameters
            
            cell.setupViews()
            cell.fetch(request: ListOfferView.Request.nearby)
           
            
            current_View = cell
            
        }
        
        
        
        
        if let __req_store = parameters["__req_store"]{
            
            if let id = Int(__req_store), id > 0{
                topBarTitle.isUserInteractionEnabled = true
                let tap = UITapGestureRecognizer(target: self, action: #selector(topOnTopBarTitle))
                topBarTitle.isUserInteractionEnabled = true
                topBarTitle.addGestureRecognizer(tap)
            }
           
        }

    
    }
    
    @objc func topOnTopBarTitle(sender:UITapGestureRecognizer) {
        if let __req_store = parameters["__req_store"]{
            startStoreDetailVC(store_id: Int(__req_store)!)
        }
    }
    
    
    func startStoreDetailVC(store_id: Int) {
        
        let sb = UIStoryboard(name: "StoreDetail", bundle: nil)
        if sb.instantiateInitialViewController() != nil {
            
            let ms: StoreDetailViewController = sb.instantiateViewController(withIdentifier: "storedetailVC") as! StoreDetailViewController
            ms.storeId = store_id
            ms.modalPresentationStyle = .fullScreen
            
            self.present(ms, animated: true)
        }
        
    }

    
    
    var defaultCat = 1
    
    func setupTopBarView() {
        
        
        var catId = Int(parameters["__req_category"]!)!
        
        if catId == 0, let c = parameters["category_id"]{
            catId = Int(c)!
        }
    
        
        if catId == 0{
            topBarView.isHidden = true
            return
        }
        
        guard let category = Category.findById(id: catId), category.parentCategory == 0 else {
            topBarView.isHidden = true
            return
        }
        
        
        //clear top bar
        cleatTopBarAllSubviews()
      
        
       
        var list_categories_obj: [FilterObjStruct] = []
        let list = Category.findByParent(parent_id: category.numCat)
        
        
        if list.count == 0{
            topBarView.isHidden = true
            return
        }
        
        defaultCat = catId
        
    
        let filter1 =  UINib(nibName: "FilterCheckBox", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! FilterCheckBox
        filter1.heightAnchor.constraint(equalToConstant: 60).isActive = true
        filter1.backgroundColor = .clear
        filter1.scrollView.backgroundColor  = .clear
        filter1.stackView.backgroundColor = .clear
        filter1.scrollView.contentInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
        
        
        filter1.isMultiple = true
        filter1.current = "select_category"
        filter1.delegate = self
        
        topBarView.isHidden = false
        
        //udate scroll Content Inset
        updateListContentInset()
        
        
        
        
        
        let object = FilterObjStruct(id: -1,
            order: -1,
            title: "All".localized,
            group: "",
            group_title: "",
            isMultiple: false
         )
        
        list_categories_obj.append(object)
        
        
        for c in list{
            
            let object = FilterObjStruct(id: c.numCat,
                order: c.numCat,
                title: c.nameCat,
                group: "",
                group_title: "",
                isMultiple: false
             )
            
            list_categories_obj.append(object)
            
        }
        
        
        var style = RadioBoxStyle()
        style.disabledBorder = .lightGray
        style.disabledBackground = Colors.white
        style.disabledText = .lightGray
        style.enabledBorder = Colors.primaryColor
        style.enabledBackground = Colors.primaryColor
        style.enabledText = .white

        filter1.setup(items: list_categories_obj, style: style)
        filter1.isMultiple = false
         
        topBarView.backgroundColor = Colors.iphoneDisplayMode
        topBarView.addSubview(filter1)
        
       filter1.toggle(id: -1)
        
        filter1.translatesAutoresizingMaskIntoConstraints = false
        let constraints = [
            filter1.topAnchor.constraint(equalTo: topBarView.topAnchor, constant: 0),
            filter1.leadingAnchor.constraint(equalTo: topBarView.leadingAnchor, constant: 0),
            filter1.bottomAnchor.constraint(equalTo: topBarView.bottomAnchor, constant: 0),
            filter1.trailingAnchor.constraint(equalTo: topBarView.trailingAnchor, constant: 0),
        ]
        NSLayoutConstraint.activate(constraints)
        
    }
   
    
    func onClicked(current: String, selected_items: [Int]) {
        
        if(selected_items.count == 0){
            return
        }

        let catId = selected_items[0]
        if catId > 0{
            let category = Category.findById(id: selected_items[0])
            parameters["__req_category"] = String(selected_items[0])
            renderResult(title: "Result for %@".localized.format(arguments: category!.nameCat.localized))
        }else{
            
            parameters["__req_category"] = String(defaultCat)
            renderResult(title: "Result for %@ ".localized.format(arguments: current_module.localized))
        }
        
        //udate scroll Content Inset
        updateListContentInset()
        
    }
    
    func updateListContentInset(){
        if(current_module == AppConfig.HomeStruct.Tags.TAG_STORES){
            let view: ListStoresView = current_View as! ListStoresView
            view.collectionView.contentInset = UIEdgeInsets(top: 55, left: 0, bottom: 0, right: 0)
            view.collectionView.layoutIfNeeded()
        }else if(current_module == AppConfig.HomeStruct.Tags.TAG_PRODUCTS){
            let view: ListProductView = current_View as! ListProductView
            view.collectionView.contentInset = UIEdgeInsets(top: 55, left: 0, bottom: 0, right: 0)
            view.collectionView.layoutIfNeeded()
        }else if(current_module == AppConfig.HomeStruct.Tags.TAG_OFFERS){
            let view: ListOfferView = current_View as! ListOfferView
            view.collectionView.contentInset = UIEdgeInsets(top: 55, left: 0, bottom: 0, right: 0)
            view.collectionView.layoutIfNeeded()
        }
        
        
    }
    
    func cleatTopBarAllSubviews() {
        
       // perform a loop to iterate each subView
       topBarView.subviews.forEach { subView in
            
       // removing subView from its parent view
          subView.removeFromSuperview()
       }
    }

    
}







