//
//  ListStoresCell.swift
//  NearbyStores
//
//  Created by Amine on 5/30/18.
//  Copyright © 2018 Amine. All rights reserved.
//

import UIKit
import SwiftEventBus
import AssistantKit

enum ListViewStyle {
    case Grid
    case List
}

class BaseView:  UIView {
    
    var viewController: UIViewController? = nil
    var isFetched = false
   
    func onListStyleChanged(style: ListViewStyle){
        
        
        
    }

    enum Request {
        static let defaultRequest = "recent"
        static let saved = -1
    }
    
    func setupViews() {
       
    }
    
    func fetch(request: String) {
        
    }
}

class ListStoresView: BaseView, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, StoreLoaderDelegate, EmptyLayoutDelegate, ErrorLayoutDelegate {

    //request
    var __req_category: Int = 0
    var __req_redius: Int = AppConfig.distanceMaxValue
    var __req_search: String = ""
    var __req_page: Int = 1

    var __req_lat: Double?
    var __req_lng: Double?


    //RESULT
    var GLOBAL_COUNT: Int = 0
    var LIST: [Store] = [Store]()
    
    var extra_parameters: [String: String] = [:]
    

    //Declare User For Current Session
    var myUserSession: User? = nil


    //Cell ID for collection
    var cellId = "storeCellId"


    //instance for scrolling
  
    lazy var collectionView: UICollectionView = {
        
        
        let layout = UICollectionViewFlowLayout()
        var cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
     

        cv.backgroundColor = Colors.bg_gray_100

        if let flowLayout = cv.collectionViewLayout as? UICollectionViewFlowLayout {
            if Device.isPad {
                flowLayout.minimumLineSpacing = 0
            } else {
                flowLayout.minimumLineSpacing = 5
            }
        }
    
        cv.dataSource = self
        cv.delegate = self
        return cv

    }()


    var viewManager: LoaderViewManager = LoaderViewManager()

    

    override func setupViews() {
      
        if #available(iOS 10.0, *) {
            collectionView.refreshControl = refreshControl
        } else {
            collectionView.addSubview(refreshControl)
        }

        // Configure Refresh Control
        refreshControl.addTarget(self, action: #selector(refreshData(_:)), for: .valueChanged)
    }

    private let refreshControl = UIRefreshControl()


    override func fetch(request: String) {
        
        if let session = Session.getInstance(), let user = session.user {
            myUserSession = user
        }

        isFetched = true

        Utils.printDebug("Fetch ListStores")

        addSubview(collectionView)
        addConstraintsWithFormat(format: "H:|[v0]|", views: collectionView)
        addConstraintsWithFormat(format: "V:|[v0]|", views: collectionView)

        collectionView.register(UINib(nibName: "StoreCell", bundle: nil), forCellWithReuseIdentifier: cellId)


        load()


        //get params
        SwiftEventBus.onMainThread(self, name: "on_search_stores") { result in

            if let object = result?.object {

                let array: [String: String] = object as! [String: String]

                self.__req_lat = nil
                self.__req_lng = nil
                
                self.__req_redius = Int(array["radius"]!)!
                self.__req_search = array["search"]!
                self.__req_page = 1

                if let cat = array["category"] {
                    self.__req_category = Int(cat)!
                }

                if let lat = array["req_lat"] {
                    self.__req_lat = Double(lat)!
                }

                if let lng = array["req_lng"] {
                    self.__req_lng = Double(lng)!
                }

                self.viewManager.showAsLoading()
                self.load()


            }

        }


        //setup view loader, Error, Empty layouts
        viewManager.setup(parent: self)
        viewManager.getEmptyLayout().delegate = self
        viewManager.getErrorLayout().delegate = self


    }


    @objc private func refreshData(_ sender: Any) {
        //Init params
        __req_page = 1
        __req_lat = nil
        __req_lng = nil
        __req_category = 0
        __req_search = ""

        // Fetch Data
        load()
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)
                    -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! StoreCell


        cell.setupSettings()
        cell.setup(object: LIST[indexPath.item])


        return cell
    }


    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let store = self.LIST[indexPath.row]
        store.save()

        
        if Constances.Application.openStoreToProductlist{
            startRecentProductResultController(storeId: store.id)
        }else{
            if let controller = self.viewController {
                  let sb = UIStoryboard(name: "StoreDetail", bundle: nil)
                  if sb.instantiateInitialViewController() != nil {

                      let ms: StoreDetailViewController = sb.instantiateViewController(withIdentifier: "storedetailVC") as! StoreDetailViewController
                      ms.storeId = store.id

                      controller.present(ms, animated: true)
                  }
              }
        }
       
        
    }
    
    func startRecentProductResultController(storeId: Int) {
        
        
        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.request = ListProductView.Request.recent
        
        if let store = Store.findById(id: storeId){
            ms.config.custom_title = store.name
        }
        
        ms.config.backHome = true
        ms.config.customToolbar = true
        
        ms.parameters["__req_store"] = String(storeId)
        
        if let controller = viewController{
             controller.present(ms, animated: true)
        }
        
        
    }


    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return LIST.count
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {


    }


    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {


        if Device.isPhone {
            let finalHeight = frame.width / 1.7
            let finalWidth = frame.width - 20
            return CGSize(width: finalWidth, height: finalHeight)
        } else if Device.isPad {
            let finalHeight = (frame.width / 3)
            let finalWidth = (frame.width / 2) - 11
            return CGSize(width: finalWidth, height: finalHeight)
        } else {
            let finalHeight = frame.width / 1.7
            let finalWidth = frame.width - 20
            return CGSize(width: finalWidth, height: finalHeight)
        }


    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

        if Device.isPad {

            if Device.screen == .inches_9_7 {
                return UIEdgeInsets(top: 10, left: 6, bottom: 0, right: 6)
            } else {
                return UIEdgeInsets(top: 20, left: 6, bottom: 0, right: 6)
            }

        } else {
            return UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0)
        }

    }


    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {

        //item = 10, count = 10 , COUNT = 23

        Utils.printDebug(" Paginate \((indexPath.item + 1)) - \(LIST.count) - \(GLOBAL_COUNT)")

        if indexPath.item + 1 == LIST.count && LIST.count < GLOBAL_COUNT && !isLoading {
            Utils.printDebug(" Paginate! \(__req_page) ")
            self.load()
        }

    }

    private var isLoading = false


    //API

    var storeLoader: StoreLoader = StoreLoader()

    func load() {

        if __req_page == 1 {
            //self.refreshControl.beginRefreshing()
            make_as_loader()
        } else {
            self.viewManager.showAsLoading()
        }


        self.storeLoader.delegate = self

        //Get current Location

        var parameters = [
            "limit": "10"
        ]

        if let lat = __req_lat, let lng = __req_lng {

            parameters["latitude"] = String(describing: lat)
            parameters["longitude"] = String(describing: lng)

        } else if let guest = Guest.getInstance() {

            parameters["latitude"] = String(guest.lat)
            parameters["longitude"] = String(guest.lng)

        }

        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)

        
        for (k, v) in extra_parameters{
            parameters[k] = v
        }
        
        if let order = extra_parameters["__req_order"]{
            parameters["order_by"] = order
        }


        Utils.printDebug("\(parameters)")

        self.isLoading = true
        self.storeLoader.load(url: Constances.Api.API_USER_GET_STORES, parameters: parameters)


    }


    func success(parser: StoreParser, response: String) {


        if(self.__req_page == 1){
            self.make_as_result()
        }
       
        self.viewManager.showMain()
        self.refreshControl.endRefreshing()

        if parser.success == 1 {


            let stores = parser.parse()


            self.GLOBAL_COUNT = parser.count

            if stores.count > 0 {

                Utils.printDebug("We loaded \(stores.count)")


                if self.__req_page == 1 {
                    self.LIST = stores
                } else {
                    self.LIST += stores
                }

                self.collectionView.reloadData()

                if self.LIST.count < self.GLOBAL_COUNT {
                    self.__req_page += 1
                }


            } else {

                if self.LIST.count == 0 {

                    emptyAndReload()
                    //show emty layout
                    viewManager.showAsEmpty()

                } else if self.__req_page == 1 {

                    emptyAndReload()

                    viewManager.showAsEmpty()

                    Utils.printDebug("===> Is Empty!")
                }


            }

        } else {

            if let errors = parser.errors {

                Utils.printDebug("===> Request Error with Messages! ListStores")
                Utils.printDebug("\(errors)")

                viewManager.showAsError()

            }

        }
        
        
        self.isLoading = false


    }

    func emptyAndReload() {

        self.LIST = []
        self.GLOBAL_COUNT = 0
        self.collectionView.reloadData()

    }

    func error(error: Error?, response: String) {

        self.isLoading = false
        self.refreshControl.endRefreshing()
        self.viewManager.showAsError()

        Utils.printDebug("===> Request Error! ListStores")
        Utils.printDebug("\(response)")

    }


    func onReloadAction(action: ErrorLayout) {

        self.viewManager.showAsLoading()

        __req_search = ""
        __req_page = 1
        __req_page = 1
        __req_lat = nil
        __req_lng = nil
        __req_category = 0
        __req_search = ""

        load()

    }

    func onReloadAction(action: EmptyLayout) {

        self.viewManager.showAsLoading()

        __req_search = ""
        __req_page = 1
        __req_search = ""
        __req_page = 1
        __req_page = 1
        __req_lat = nil
        __req_lng = nil
        __req_category = 0
        __req_search = ""
        

        load()

    }


}



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


extension ListStoresView {
    
    @available(iOS 14.0, *)
    private func configureDataSource() {
        let cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, String> { (cell, indexPath, item) in
            var content = cell.defaultContentConfiguration()
            content.text = "hhhhhhhh"
            
            cell.contentConfiguration = content
        }
        
    }
    
    
    enum Request {
        static let nearby = "nearby"
        static let featured = "featured"
        static let recent = "recent"
        static let saved = "saved"
        static let own = "own"
        static let top_rated = "top_rated"
        static let top_seller = "top_seller"
        static let nearby_top_rated = "nearby_top_rated"
    }
}

struct MyLocation{
    static var isProvided = false
}

