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

import UIKit
import SwiftEventBus
import RealmSwift
import AssistantKit
import SwiftIcons
import SwiftWebVC



struct OrderStatus {
    static let ALL = -1
    static let PENDING = 1
    static let CONFIRMED = 2
    static let PREPARING = 3
    static let ON_DELIVERY = 4
    static let DELIVERED = 5
    static let CANCELLED = 6
    static let REPORTED = 7
}

class BaseView:  UIView {
    
    var viewController: UIViewController? = nil
    var isFetched = false
    
    enum Request {
        static let recent = "recent"
        static let nearby = "nearby"
    }
    
    func setupViews() {
       
    }
    
    func fetch(request: String) {
        
    }
}

class ListOrderCell: BaseView, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource , OrderLoaderDelegate, EmptyLayoutDelegate, ErrorLayoutDelegate,CustomLayoutDelegate, OrderCellDelegate{
 

    var viewNavigationController: UINavigationController? = nil
    var viewTabBarController: UITabBarController? = nil
    
   
    enum Request {
        static let nearby = "nearby"
        static let recent = "recent"
    }
    
    //request
    var __req_limit: Int = 20
    var __req_redius: Int  = AppConfig.distanceMaxValue
    var __req_list: String = Request.nearby
    var __req_page: Int = 1
    var __req_delivery_id: Int = 0
    var __req_store: Int = 0
    var __req_delivery_status: Int = OrderDeliveryStatus.PENDING
    var __req_order_status: Int = OrderStatus.ALL
    var __req_except: String = ""
    
    //RESULT
    var GLOBAL_COUNT: Int = 0
    var LIST: [Order] = [Order]()
    
    //Declare User For Current Session
    var myUserSession: User? = nil
    
    
    //Cell ID for collection
    var cellId = "orderCellId"
    
    
    //instance for scrolling
   
    lazy var collectionView: UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        
    
        cv.backgroundColor = Colors.bg_gray_100
    
        if let flowLayout = cv.collectionViewLayout as? UICollectionViewFlowLayout {
            flowLayout.minimumLineSpacing = 5
        }
        
        cv.dataSource = self
        cv.delegate = self
        return cv
        
    }()
    
    
    var viewManager: LoaderViewManager =  LoaderViewManager()
    
    
    override func setupViews() {
        super.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
        }
        
        
        
        Utils.printDebug("Fetch ListOrders")
        
        addSubview(collectionView)
        addConstraintsWithFormat(format: "H:|[v0]|", views: collectionView)
        addConstraintsWithFormat(format: "V:|[v0]|", views: collectionView)
        
        collectionView.register(UINib(nibName: "OrderCell", bundle: nil), forCellWithReuseIdentifier: cellId)
        collectionView.backgroundColor = Colors.iphoneDisplayMode
        

        
        //setup view loader, Error, Empty layouts
     
        viewManager.setup(parent: self)
        viewManager.getEmptyLayout().delegate = self
        viewManager.getErrorLayout().delegate = self
        viewManager.getCustomLayout().delegate = self
        
        viewManager.getEmptyLayout().header.numberOfLines = 0
        viewManager.getEmptyLayout().messageError.numberOfLines = 0

        viewManager.getErrorLayout().header.numberOfLines = 0
        viewManager.getErrorLayout().messageError.numberOfLines = 0
        
        
        isFetched = true
        
        refreshControl.beginRefreshing()
        load()
        
     
        onReceiveListener()
        
    }
    
    
  
    
    func setupCustomLayoutButton() {

        //let refreshIcon = UIImage.init(icon: .linearIcons(.undo), size: CGSize(width: 35, height: 35), textColor: .red)
        viewManager.getCustomLayout().customBtn.initDefaultFont()
        viewManager.getCustomLayout().customBtn.setTitleColor(Colors.primaryColor, for: .normal)
        viewManager.getCustomLayout().customBtn.setTitle("Refresh".localized, for: .normal)
        
        
        viewManager.getCustomLayout().customBtn.setIcon(prefixText: "", prefixTextColor: Colors.primaryColor, icon: .linearIcons(.undo), iconColor: Colors.primaryColor, postfixText: "  "+"Refresh".localized, postfixTextColor: Colors.primaryColor, forState: .normal, textSize: 15, iconSize: 15)


        viewManager.getCustomLayout().customText.initBolodFont(size: 22)
        viewManager.getCustomLayout().customText.text = "No order found!".localized
        viewManager.getCustomLayout().customText.numberOfLines = 0
        
    
        
    }
    
    func checker() {
    
        self.viewManager.showResult()
        /*if Session.isLogged() == false {
            self.setupCustomLayoutChatLogin()
            self.viewManager.showAsCustomLayout()
        }else{
            self.viewManager.showMain()
        }*/
    }
    
    func onReceiveListener() {
        
        //get params
        SwiftEventBus.onMainThread(self, name: "on_receive_message") { result in
            
            if let object = result?.object{
                
            
                
            }
            
        }
        
        
        //get params
       SwiftEventBus.onMainThread(self, name: "on_refresh") { result in
            
            if let object = result?.object{
                self.viewManager.showAsLoading()
                self.__req_page = 1
                self.load()
            }
            
        }
        
        
 
    }
    
    @objc private func refreshData(_ sender: Any) {
        
        if Session.isLogged() {
            //Init params
            __req_page = 1
            
            // Fetch Data
            load()
            
        }else{
            self.viewManager.showAsCustomLayout()
        }
       
    }
    

    
    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 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 {
        
        let object = LIST[indexPath.row]

        var item_size = CGFloat(0)
        
        let d  = ( object.items.count+2 )
        
    
        
        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: self.frame.width-(5+5), height: (60+item_size))
    }


    
    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 && self.__req_limit > 1 {
            Utils.printDebug(" Paginate! \(__req_page) ")
            self.load()
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 5, left: 5, bottom: 0, right: 5)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {


    }
    
  
   
    private var isLoading = false
    //API
    
    var orderLoader: OrderLoader = OrderLoader()
    
    func load () {
        
        if let session = Session.getInstance(), let user = session.user{
            myUserSession = user
        }
        
        if __req_page == 1 {
            self.refreshControl.beginRefreshing()
        }else{
            self.viewManager.showAsLoading()
        }
        
        
        self.orderLoader.delegate = self
        
        //Get current Location
        var parameters = [
            "limit"          : String(self.__req_limit),
        ]
        
        if let guest = Guest.getInstance(){
            parameters["auth_type"] = "guest"
            parameters["auth_id"] = String(guest.id)
        }
        
        parameters["page"] = String(__req_page)
        parameters["delivery_status"] = String(__req_delivery_status)
        parameters["order_status"] = String(__req_order_status)
        parameters["except"] = String(__req_except)
        parameters["delivery_id"] = String(__req_delivery_id)
        
       
        if __req_list == Request.nearby, let guest = Guest.getInstance(){
            parameters["latitude"] = String(guest.lat)
            parameters["longitude"] = String(guest.lng)
            parameters["order_by"] = Request.nearby
        }else{
            parameters["order_by"] = Request.recent
        }
       
    
        Utils.printDebug("\(parameters)")
        
        self.isLoading = true
        self.orderLoader.load(url: OrderConstances.Api.API_GET_ORDERS, parameters: parameters)
        
    }
    
    private func open_first(){
        
        if LIST[0].is_open{
            LIST[0].is_open = false
        }else{
            LIST[0].is_open = true
        }
        
    
        
        let indexpath = IndexPath(item: 0, section: 0)
        collectionView.reloadItems(at: [indexpath])
        collectionView.scrollToItem(at: indexpath, at: [.centeredVertically, .centeredHorizontally], animated: true)
        
        
    }
    
    func success(parser: OrderParser,response: String) {
        
       Utils.printDebug("response \(response)")
        
        self.viewManager.showResult()
        self.refreshControl.endRefreshing()
        
        
        self.isLoading = false
        
        if parser.success == 1 {
            
            
            let orders = parser.parse()
            
            self.GLOBAL_COUNT = parser.count
            
            if orders.count > 0 {
            
                
                Utils.printDebug("Data loaded \(orders)")
                
                
                if self.__req_page == 1 {
                    self.LIST = orders
                    self.LIST[0].is_open = true
                }else{
                    self.LIST += orders
                }
                
               // self.LIST.saveAll()
                self.collectionView.reloadData()
                
                if self.LIST.count < self.GLOBAL_COUNT {
                    self.__req_page += 1
                }
                
            
                
            }else{
                
                if self.LIST.count == 0 {
                    
                    emptyAndReload()
                    //show emty layout
                    self.viewManager.showAsEmpty()
                    self.viewManager.getEmptyLayout().messageError.text = "No order found".localized
                    
                }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! ListOrders")
                Utils.printDebug("\(errors)")
                
                viewManager.showAsError()
                
            }
            
        }
        
    }
    
    func emptyAndReload()  {
        
        self.LIST = []
        self.GLOBAL_COUNT = 0
        self.collectionView.reloadData()
        
    }
    
    func error(error: Error?,response: String) {
        
        self.isLoading = false
        self.refreshControl.endRefreshing()
        
        if self.LIST.count == 0{
            self.viewManager.showAsError()
        }
        
        Utils.printDebug("===> Request Error! ListOrders")
        Utils.printDebug("\(response)")
        
    }
    
    
    func onReloadAction(action: ErrorLayout) {
        
       
        self.viewManager.showAsLoading()
        
        __req_page = 1
        
        load()
        
    }
    
    func onReloadAction(action: EmptyLayout) {
        
        self.isLoading = false
        self.viewManager.showAsLoading()
        self.__req_page = 1
        self.load()
        
    }
    
    func onReloadAction(action: CustomLayout) {
        
       self.isLoading = false
       self.viewManager.showAsLoading()
       self.__req_page = 1
       self.load()
        
    }
    
    
   
    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) {
           
        
     
    }
    
    
    func onButtonsPressed(order: Order,ocid: Int) {
        
        guard let sess = Session.getInstance(), let user = sess.user else {
            return
        }
        
        
    
    
        if(ocid == 1){ //accept order
            
            if let value = SyncAppConfig.findById(id: "USER_PHONE_VERIFICATION"), value.getValue(defaultValue: false), user.phoneVerified == 0  {
                if let vc = self.viewController{
                        vc.showAlertInitError(title: "Phone verification".localized, msg: "Please verify your phone number", msgBnt: "Verify".localized)  {
                            let sb = UIStoryboard(name: "EditProfile", bundle: nil)
                            if sb.instantiateInitialViewController() != nil {
                                let ms: EditProfileViewController = sb.instantiateViewController(withIdentifier: "editprofileVC") as! EditProfileViewController
                                vc.present(ms, animated: true)
                            }
                        }
                    }
                return
            }
        
            if user.status == -1{
                if let vc = self.viewController{
                    vc.showAlertInitError(title: "Alert!".localized, msg: "your account is still pending approval".localized, msgBnt: "OK".localized)  {
                            
                        }
                    }
                    
                return
            }
            
           
            let alert = UIAlertController(title: "Order".localized, message: nil, preferredStyle: .actionSheet)
            
            alert.addAction(UIAlertAction(title: "Accept".localized, style: .default) { _ in
                //call api
                
                //make it as ongoing
                let parameters = [
                    "order_id": order.id,
                    "status": OrderDeliveryStatus.ONGOING,
                    "delivery_id": user.id,
                ]
                
                self.viewManager.showAsLoading()
              
                let api = SimpleRequestApi()
                api.run(url: OrderConstances.Api.API_DELIVERY_UPDATE_STATUS, parameters: parameters) { (parser) in
                
                    self.viewManager.showResult()
                    
                    if parser?.success == 1{
                        
                       
                        let realm = try! Realm()
                        realm.beginWrite()
                        order.delivery_status = OrderDeliveryStatus.ONGOING
                        try! realm.commitWrite()
                        
                        order.save()
                        
                        
                        self.startOrderDetailVC(order: order)
                        
                        self.LIST = []
                        self.collectionView.reloadData()
                        
                        self.__req_page = 1
                        self.load()
                        
                        
                        //move to the manager orders list
                        SwiftEventBus.post("set_active_page", sender: AppConfig.Tabs.Tags.TAG_MANAGED_ORDER)
                    }
                    
                 
                }
                
                
            })
            
            alert.addAction(UIAlertAction(title: "Decline".localized, style: .default) { _ in
                
                //save id & refresh
        
                var declined_orders = LocalData.getValue(key: "declined_orders",defaultValue: "")
                    
                if declined_orders == ""{
                    declined_orders = declined_orders+"\(order.id)"
                }else{
                    declined_orders = declined_orders+";\(order.id)"
                }
                
                LocalData.setValue(key: "declined_orders", value: declined_orders)
               
                self.LIST = []
                self.collectionView.reloadData()
                
                //reload orders list
                self.__req_except = declined_orders
                self.__req_page = 1
                self.load()
         
                
            })
            
            
            alert.addAction(UIAlertAction(title: "Cancel".localized, style: .default) { _ in
                alert.dismiss(animated: true)
            })
            
            if let vc = viewController{
                vc.present(alert, animated: true, completion: nil)
            }
            
            
        }else if(ocid == 2){ //order detail
            
            self.startOrderDetailVC(order: order)
            
        }else if(ocid == 3){ // contact
            
            self.startOrderDetailVC(order: order)
         
        }
     
    }
    
    
    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
            
            if let vc = self.viewController{
                vc.present(ms, animated: true)
            }
  
        }
        
    }
    
}

