//
//  OrdersList.swift
//  NSApplication1.8
//
//  Created by Amine  on 5/11/20.
//  Copyright © 2020 Amine. All rights reserved.
//

import UIKit
import AssistantKit
import SwiftEventBus


class OrdersListController: MyUIViewController, EmptyLayoutDelegate, ErrorLayoutDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, OrderLoaderDelegate , OrderCellDelegate{
    
   
   
    var order_id: Int?

    //request
    var __req_page: Int = 1


    //RESULT
    var GLOBAL_COUNT: Int = 0
    var LIST: [Order] = [Order]()


    //Declare User For Current Session
    var myUserSession: User? = nil
    var viewManager: LoaderViewManager = LoaderViewManager()
    let cellId = "orderCellId"


    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var navigationBarItem: UINavigationItem!
    @IBOutlet weak var viewContainer: UIView!
    @IBOutlet weak var collectionView: UICollectionView!


    func setupNavBarButtons() {

        let color = AppDesignUtils.defaultModeColor(dark: .white, light: 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)
               
        
        
        navigationBarItem.leftBarButtonItems = []
        navigationBarItem.rightBarButtonItems = []
        navigationBarItem.leftBarButtonItems?.append(customBarButtonItem)

    }

    let topBarTitle: EdgeLabel = {

        let titleLabel = EdgeLabel()

        titleLabel.text = ""
        titleLabel.textColor = UIColor.white
        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 = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.primaryColor)
        topBarTitle.font = UIFont(name: AppConfig.Design.Fonts.regular, size: 17)
        topBarTitle.leftTextInset = 5

        topBarTitle.text = "My orders".localized

        navigationBarItem.titleView = topBarTitle

    }

    @objc func onBackHandler() {
        self.dismiss(animated: true)
    }


    func setupCollectionView() {

        if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            flowLayout.minimumLineSpacing = 1
            self.view.layoutIfNeeded()
        }


        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = Colors.bg_gray_100
        collectionView.register(UINib(nibName: "OrderCell", bundle: nil), forCellWithReuseIdentifier: cellId)


    }


    override func viewDidLoad() {
        super.viewDidLoad()


        if let session = Session.getInstance(), let user = session.user {
            myUserSession = user
        }

        self.view.backgroundColor = Colors.bg_gray_100


        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
        setupNavBarButtons()

        setupCollectionView()

        setupRefreshControl()
    
        setupViewloader()
        
        load()
        
        //get params
        SwiftEventBus.onMainThread(self, name: "payment_done") { result in
            
            self.__req_page = 1
            self.load()

        }

    }
    
    
       func setupViewloader()  {
           
           //setup view loader, Error, Empty layouts
           viewManager.setup(parent: viewContainer)
           viewManager.getEmptyLayout().delegate = self
           viewManager.getErrorLayout().delegate = self
           
           if Session.isLogged() ==  false {
               return
           }else{
               
           }
       }


    @objc private func refreshData(_ sender: Any) {

        self.__req_page = 1
        load()

    }


    private let refreshControl = UIRefreshControl()

    func setupRefreshControl() {

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

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

    }


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


        let object = LIST[indexPath.row]
        let cell: OrderCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! OrderCell
        
    
       

        cell.setupSettings()
        cell.setup(order: object)
        cell.delegate = self

        return cell

    
    }
    
    func onPayNow(order: Order) {
        
        
        let sb = UIStoryboard(name: "PaymentSelectorController", bundle: nil)
        let ms: PaymentSelectorController = sb.instantiateViewController(withIdentifier: "payment_selector_VC") as! PaymentSelectorController
        
        ms.order = order

        self.present(ms, animated: true)
        
    }
    
    func onOrderDetailPressed(order: Order) {
        
        self.startOrderDetailVC(order: order)
        
    }
    
    
    func onPressed(id: Int) {
           
        if let index = LIST.getindex(order_id: id){
            
            let size = LIST.count - 1
            if size >= 0 {
                for j in 0...size {
                    if(j != index){
                        LIST[j].is_open = false
                        let indexpath0 = IndexPath(item: j, section: 0)
                        collectionView.reloadItems(at: [indexpath0])
                    }
                }
            }
            
            if LIST[index].is_open{
                LIST[index].is_open = false
            }else{
                LIST[index].is_open = true
            }
            
            let indexpath = IndexPath(item: index, section: 0)
            collectionView.reloadItems(at: [indexpath])
            collectionView.scrollToItem(at: indexpath, at: [.centeredVertically, .centeredHorizontally], animated: true)
            
        }
        
        
    }
    
    
    func onProductPressed(id: Int, module: String) {
           
        let sb = UIStoryboard(name: "ProductDetail", bundle: nil)
        let ms: ProductDetailViewController = sb.instantiateViewController(withIdentifier: "productdetailVC") as! ProductDetailViewController
        ms.product_id = id
        self.present(ms, animated: true)
        
    }
       


    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let object = LIST[indexPath.row]

        var item_size = CGFloat(0)
        
        var d  = ( object.items.count+1 )
        
        if(object.invoice > 0){
           d  = d+1
        }else{
            d  = d+1
        }
    
        
        if(object.is_open){
            
            item_size = CGFloat(70*d)
            
            let extras = OrderParser.parse_extras(order: object)
            
            if(extras.count > 0){
                item_size = item_size + CGFloat(( extras.count * 30 ) + 30)
            }
            
        }else{
            item_size  = CGFloat(0)
        }
        
        
        
        
        
    
        return CGSize(width: view.frame.width, height: (60+item_size))
    }


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


    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }


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

        

    }


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

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

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

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

    }


    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
    }


    private var isLoading = false
    //API

    var loader: OrderLoader = OrderLoader()

    func load() {

        self.viewManager.showAsLoading(parent: collectionView)

        self.loader.delegate = self

        //Get current Location

        var parameters = [
            "limit": "20"
        ]
        
        if let sess = Session.getInstance(), let user = sess.user{
            parameters["user_id"] = "\(user.id)"
        }

        parameters["page"] = String(describing: self.__req_page)

        Utils.printDebug("\(parameters)")

        self.isLoading = true
        self.loader.load(url: OrderConstances.Api.API_GET_ORDERS, parameters: parameters)


    }


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


        self.refreshControl.endRefreshing()

        self.viewManager.showMain()
        //self.refreshControl.endRefreshing()

        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
            self.isLoading = false
        }


        if parser.success == 1 {

            let orders = parser.parse()

            
            Utils.printDebug("===> \(orders)")

            orders.saveAll()
            
            Utils.printDebug("===> \(orders)")

          
            if orders.count > 0 {
             
                if self.__req_page == 1 {

                    self.LIST = orders
                    self.GLOBAL_COUNT = parser.count

                } else {

                    self.LIST += orders
                    self.GLOBAL_COUNT = parser.count

                }

               
               

                self.collectionView.reloadData()

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

                if let oid = self.order_id{
                    self.onPressed(id: oid)
                    self.order_id = nil
                }


            } else {

                if self.LIST.count == 0 && self.__req_page == 1 {
                    emptyAndReload()
                    //show emty layout
                    viewManager.showAsEmpty()
                }

            }

        } else {

            if let errors = parser.errors {

                if self.LIST.count == 0 {
                    Utils.printDebug("\(errors)")
                    viewManager.showAsError()
                }


            }

        }

    }
    



    func emptyAndReload() {

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

    }

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

        self.refreshControl.endRefreshing()


        if self.LIST.count == 0 {

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

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

        }

    }


    func onReloadAction(action: ErrorLayout) {

        Utils.printDebug("onReloadAction ErrorLayout")

        self.viewManager.showAsLoading(parent: collectionView)

        __req_page = 1

        load()

    }

    func onReloadAction(action: EmptyLayout) {


        self.viewManager.showAsLoading(parent: collectionView)

        __req_page = 1

        load()

    }


    static func startController(viewController: UIViewController) {

        let sb = UIStoryboard(name: "OrdersList", bundle: nil)
        let ms: OrdersListController = sb.instantiateViewController(withIdentifier: "ordersListVC") as! OrdersListController

        viewController.present(ms, animated: true)

    }

    
    func startOrderDetailVC(order: Order) {
        
        let sb = UIStoryboard(name: "OrderDetail", bundle: nil)
        if sb.instantiateInitialViewController() != nil {
            
            let ms: OrderDetailViewController = sb.instantiateViewController(withIdentifier: "order_detail_VC") as! OrderDetailViewController
            
            ms.order = order
            
            present(ms, animated: true)
  
        }
        
    }

}
