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

import UIKit
import SwiftEventBus
import AssistantKit
import StepIndicator


class OrderViewController: MyUIViewController, EmptyLayoutDelegate, ErrorLayoutDelegate, MakePaymentControllerDelegate{
   
 
    var orderID: Int?
    //Declare User For Current Session
    var myUserSession: User? = nil
    var viewManager: LoaderViewManager =  LoaderViewManager()
    var cart:Cart? = nil

    @IBOutlet weak var stepIndicatorView: StepIndicatorView!
    @IBOutlet weak var buttons_container: UIView!
    @IBOutlet weak var next_btn: UIButton!
    @IBOutlet weak var prev_btn: UIButton!
    
    
    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var navigationBarItem: UINavigationItem!
    @IBOutlet weak var viewContainer: UIView!
    @IBOutlet weak var order_container: UIView!
    
    @IBAction func prevAction(_ sender: Any) {
        if(current_page > 1){
            current_page = current_page-1
            next_page(title: titles[(current_page-1)], page: current_page)
        }
    }
    
    @IBAction func nexAction(_ sender: Any) {
        
        current_page = current_page+1
        
        if(current_page <= pages.count){
            
            if(current_page == 3 && !ModuleManager.isEnabled(module: "order_payment")){
                
                
                
                let OrderFormView = self.order_container.subviews[0] as! OrderFormView
                let parameters = OrderFormView.getParameters()
                
                let ConfirmOrderView = self.order_container.subviews[1] as! ConfirmOrderView
                let products = ConfirmOrderView.productList
            

                Utils.printDebug("\(products)")
                   
            
                if let cf = OrderFormView.cf{
                    send_order(cf_id: cf.id,cf_data: parameters, productList: products)
                }else{
                     send_order(cf_id: 0,cf_data: parameters, productList: products)
                }
                
                                                           
                        
                
                
                self.current_page = self.current_page-1
                
                
            }else if(current_page == 4 && ModuleManager.isEnabled(module: "order_payment")){
                
                
                let OrderFormView = self.order_container.subviews[0] as! OrderFormView
                let parameters = OrderFormView.getParameters()
                
                let ConfirmOrderView = self.order_container.subviews[1] as! ConfirmOrderView
                let products = ConfirmOrderView.productList
                

                Utils.printDebug("\(products)")
                   
                
                 if let cf = OrderFormView.cf{
                    send_order(cf_id: cf.id,cf_data: parameters, productList: products)
                 }else{
                    send_order(cf_id: 0,cf_data: parameters, productList: products)
                }
                
                
                self.current_page = self.current_page-1
                
                
            }else{
                next_page(title: titles[(current_page-1)], page: current_page)
            }
            
        }else{
            dismiss(animated: true)
        }
        
    }
    
    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: .googleMaterialDesign(.close), size: CGSize(width: 30, height: 30), textColor: color)
        }else{
            arrowImage = UIImage.init(icon: .googleMaterialDesign(.close), size: CGSize(width: 30, height: 30), textColor: color)
        }
        
        
        let customBarButtonItem = UIBarButtonItem(image: arrowImage!, style: .plain, target: self, action: #selector(onBackHandler))
        
      
    
        navigationBarItem.leftBarButtonItems = []
        navigationBarItem.rightBarButtonItems = []
        navigationBarItem.leftBarButtonItems?.append(customBarButtonItem)
       
    }
    
    
    func setupStepsIndicator() {
       
        self.stepIndicatorView.circleColor = UIColor(red: 179.0/255.0, green: 189.0/255.0, blue: 194.0/255.0, alpha: 1.0)
        self.stepIndicatorView.circleTintColor = UIColor(red: 0.0/255.0, green: 180.0/255.0, blue: 124.0/255.0, alpha: 1.0)
        self.stepIndicatorView.circleStrokeWidth = 3.0
        self.stepIndicatorView.circleRadius = 10.0
        self.stepIndicatorView.lineColor = self.stepIndicatorView.circleColor
        self.stepIndicatorView.lineTintColor = self.stepIndicatorView.circleTintColor
        self.stepIndicatorView.lineMargin = 4.0
        self.stepIndicatorView.lineStrokeWidth = 2.0
        //self.stepIndicatorView.numberOfSteps = 3
        self.stepIndicatorView.displayNumbers = false //indicates if it displays numbers at the center instead of the core circle
        self.stepIndicatorView.direction = .leftToRight //four directions
    }
    
    
    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{
            
        }
    }


   
    override func viewDidLoad() {
        super.viewDidLoad()
    


        self.hideKeyboardWhenTappedAround()
        
        
        guard (cart?.items.count)! > 0 else {
            self.dismiss(animated: true)
            return
        }
        
        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()
        setupViewloader()
        setupStepsIndicator()
        setupButtons()
        
        setupPages()
        next_page(title: titles[0].localized, page: current_page)
       
    }
    
    
    func setupButtons(){
        
        
        self.buttons_container.backgroundColor = Colors.darkColor
        
        self.prev_btn.isHidden = false
        self.next_btn.isHidden = false
    
        
        self.prev_btn.setTitle("", for: .normal)
        self.next_btn.setTitle("Next".localized, for: .normal)
        
        self.next_btn.backgroundColor = Colors.primaryColor
        self.prev_btn.backgroundColor = Colors.darkColor
        
        self.next_btn.setTitleColor(.white, for: .normal)
        self.prev_btn.setTitleColor(.white, for: .normal)
        

        self.next_btn.initDefaultFont()
        
        
        if Utils.isRTL(){
            self.prev_btn.setIcon(icon: .ionicons(.iosArrowForward), iconSize: 25, color: .white, forState: .normal)
        }else{
            self.prev_btn.setIcon(icon: .ionicons(.iosArrowBack), iconSize: 25, color: .white, forState: .normal)
        }
        
        
        DispatchQueue.main.asyncAfter(deadline: .now()+1) {
            self.next_btn.setCustomButtonStyleDefault()
        }
      
    }
    
    var pages = ["OrderFormView","ConfirmOrderView","OrderCompletedView"]
    var titles = ["Checkout","Checkout","Checkout"]
    var button_titles = ["Next","Confim","DONE"]

    func setupPages() {
        
        
        if(ModuleManager.isEnabled(module: "order_payment")){
            pages = ["OrderFormView","ConfirmOrderView","OrderPaymentView","OrderCompletedView"]
            titles = ["Checkout","Checkout","Payment","Checkout"]
            button_titles = ["Next","Confim","Confirm Payment","DONE"]
        }
        
        
        for index in 0...(pages.count-1) {
            
            let mOrderFormView:OrderSimpleView = UINib(nibName: pages[index], bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! OrderSimpleView

            mOrderFormView.viewController = self
            mOrderFormView._store_id = cart!.items[0].item!.store_id
            mOrderFormView.setup()
            order_container.addSubview(mOrderFormView)
            order_container.addConstraintsWithFormat(format: "H:|[v0]|", views: mOrderFormView)
            order_container.addConstraintsWithFormat(format: "V:|[v0]|", views: mOrderFormView)
            
            mOrderFormView.isHidden = true
        }
        
    }
    
    
    var total = 0.0
    var total_currency: Currency? = nil
    
    
    var current_page = 1
    
    func next_page(title: String, page: Int){
        
        
        
        for index in 0...(pages.count-1) {
            let nextView = self.order_container.subviews[1]
            nextView.isHidden = true
        }
       
        if(page == 1){//details
            
            for view in self.order_container.subviews{
                view.isHidden = true
            }
            
            prev_btn.isHidden = true
            next_btn.isHidden = false
            next_btn.setTitle(button_titles[(page-1)], for: .normal)
            
            
            UIView.animate(withDuration: 0.15) { () -> Void in
                let myView = self.order_container.subviews[(page-1)] as! OrderFormView
                
                //
                if((self.cart?.items[0].item!.fields.count)!>0){
                    myView.cf = self.cart?.items[0].item!.fields.first
                    myView.setupCF()
                }
                
                myView.isHidden = false
            }
        
            stepIndicatorView.currentStep = 0
            topBarTitle.text = title
            
            
            view.layoutIfNeeded()
            
        }else if(page == 2){//confirm
            
            for view in self.order_container.subviews{
                view.isHidden = true
            }
            
            let prevView = self.order_container.subviews[0] as! OrderFormView
            let errors = prevView.getErrors()
            
            if(errors.count > 0){
                current_page = 1
                
                Utils.printDebug("\(errors)")
                
                self.showAlertError(title: "Error".localized, content: errors, msgBnt: "OK".localized)
                prevView.isHidden = false
                return
            }
    
            
            next_btn.setTitle(button_titles[(page-1)], for: .normal)
            
            
            UIView.animate(withDuration: 0.15) { () -> Void in
                
                let prevView = self.order_container.subviews[0] as! OrderFormView
                let parameters = prevView.getParameters()
                
                let nextView = self.order_container.subviews[(page-1)] as! ConfirmOrderView
          
             
                
                if let cart = self.cart{
                    nextView.updateDetail(parameters: parameters,cart:  cart)
                    self.total = nextView.total
                }
                
                nextView.isHidden = false
                
            }
         
            stepIndicatorView.currentStep = 1
            topBarTitle.text = title
            
            UIView.animate(withDuration: 0.15) { () -> Void in
                self.prev_btn.isHidden = false
                self.next_btn.isHidden = false
            }
            
            
                              
            
            view.layoutIfNeeded()
            
        }else if( page == 3 && self.total > 0 && ModuleManager.isEnabled(module: "order_payment")){//payment
            
            for view in self.order_container.subviews{
                view.isHidden = true
            }
               
                next_btn.setTitle(button_titles[(page-1)], for: .normal)
                
                UIView.animate(withDuration: 0.15) { () -> Void in
                    
                    
                    let prevView = self.order_container.subviews[1] as! ConfirmOrderView
                    let nextView = self.order_container.subviews[(page-1)] as! OrderPaymentView
                    
                    
                    Utils.printDebug("\(prevView.total)")
                    
                    nextView.setDiscount(code: prevView.codeCoupn, appliedDiscountValue: prevView.appliedDiscountedValue0)
                    nextView.updateAmount(total: prevView.total, currency: prevView.total_currency)
                
                    prevView.isHidden = true
                    nextView.isHidden = false
                    
                }
             
                topBarTitle.text = title
                
                UIView.animate(withDuration: 0.15) { () -> Void in
                    self.prev_btn.isHidden = false
                    self.next_btn.isHidden = false
                }
                
                view.layoutIfNeeded()
                
        }else if( (page == 4 || page == 3) && (self.total == 0  || !ModuleManager.isEnabled(module: "order_payment"))){//done
            
               
                next_btn.setTitle(button_titles[(page-1)], for: .normal)
                
                UIView.animate(withDuration: 0.15) { () -> Void in
                    
                    let prevView = self.order_container.subviews[1] as! ConfirmOrderView
                    let nextView = self.order_container.subviews[(page-1)] as! OrderCompletedView
                    
                    prevView.isHidden = true
                    nextView.isHidden = false
                    
                }
            
                
                stepIndicatorView.currentStep = 3
            
                topBarTitle.text = title
                
                UIView.animate(withDuration: 0.15) { () -> Void in
                    self.prev_btn.isHidden = true
                    self.next_btn.isHidden = false
                }
                
                view.layoutIfNeeded()
            
            
                //remove products from the cart
                Cart.clear()
            
                //refresh staff linked with the cart
                SwiftEventBus.post("update_cart_badge")
            
                
        }
        
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        
    }
    
    
    static var isAppear = false
    
    override func viewWillDisappear(_ animated: Bool) {
        
        
    }
    
    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 = "Order".localized
        
        navigationBarItem.titleView = topBarTitle
    
    }
    
    @objc func onBackHandler() {
        self.dismiss(animated: true)
        SwiftEventBus.post("on_main_refresh", sender: true)
    }
    
    

    private var isLoading = false
    //API

    func emptyAndReload()  {
        
       
    }
    
    
    
    
    func onReloadAction(action: ErrorLayout) {
        
        Utils.printDebug("onReloadAction ErrorLayout")
        
        
    }
    
    func onReloadAction(action: EmptyLayout) {
        
        
       
        
    }
    
    
    
    func send_order(cf_id: Int,cf_data: [KeyValue],productList: [ProductLineItem]) {
        
    
        guard productList.count>0 else {
            return
        }
        
        let products_array = parse_product_to_array(productList: productList)
        let params_array = parse_params_to_array(parameters: cf_data)

    
 
        if(!Session.isLogged()){
            return
        }
        
        
        if let order_id = self.orderID, ModuleManager.isEnabled(module: "order_payment"){
            self.get_payment_url(order_id: order_id)
            return
        }
        
    
        let api = SimpleRequestApi()
        
        var parameters = [
            "init":"true"
        ]
        
        parameters["req_cf_id"] = String(cf_id)
        
        
        parameters["module"] = "store"
        parameters["module_id"] = String(cart!.items[0].item!.store_id)
        
        if let cf = json(from: params_array){
             parameters["req_cf_data"] = cf
        }
            
        if let cart = json(from: products_array){
             parameters["cart"] = cart
        }
        
        if let sess = Session.getInstance(), let user = sess.user{
            parameters["user_id"] = "\(user.id)"
        }
        
        let mConfirmOrderView = self.order_container.subviews[1] as! ConfirmOrderView
        
        if let code = mConfirmOrderView.codeCoupn{
            parameters["couponCode"] = code
        }
        
        Utils.printDebug("\(parameters)")
        
        
        MyProgress.show()
        
               api.run(url: OrderConstances.Api.API_CREATE_ORDER, parameters: parameters) { (parser) in
               
                   if(parser?.success == 1){
                    
                    //save cf
                    //cf_id: Int,cf_data: [KeyValue]
                    for p in cf_data{
                        CustomFields.save_cache(id: cf_id, key: p.key, value: p.value)
                    }
                   
                    
                    MyProgress.dismiss()
                    
                       Utils.printDebug("\(parser)")
                    
                    if ModuleManager.isEnabled(module: "order_payment"){
                        let id = parser?.result?.intValue
                        self.orderID = id
                        self.get_payment_url(order_id: id!)
                    }else{
                        self.current_page = self.current_page+1
                        self.next_page(title: self.titles[(self.current_page-1)], page: self.current_page)
                    }
                      
                    
                }else if(parser?.success == -1){
                    
                    if let errors = parser?.errors, errors.count > 0{
                         self.showAlertError(title: "Alert".localized, content: errors, msgBnt: "OK".localized)
                    }
                   
                     MyProgress.dismiss()
                    
                }
                   
               }
        
       
        
    }
    
    func json(from object:Any) -> String? {
        guard let data = try? JSONSerialization.data(withJSONObject: object, options: []) else {
            return nil
        }
        return String(data: data, encoding: String.Encoding.utf8)
    }

    func parse_product_to_array(productList: [ProductLineItem]) -> [[String: String]] {
       
        var array: [[String: String]]  = []
        
        for p in productList{
            
            //parse variants to an json
            let variants = parse_variants_to_array(variants: p.variants)
            var variants_json = ""
            
            if let j = self.json(from: variants){
                variants_json = j
            }
            
            
           array.append([
                "module": p.module,
                "module_id": String(p.id),
                "qty": String(p.qty),
                "amount": String(p.amount_v),
                "variants": variants_json
            ])
        }
        
        return array
        
    }
    
    func parse_params_to_array(parameters: [KeyValue]) -> [String: String] {
       
        var array: [String: String]  = [:]
        
        
        
        for p in parameters{
            array[p.key] = p.value
        }
        
        return array
        
    }
    
    
    func parse_variants_to_array(variants: [V_GroupResult]) -> [String: [String: String]] {
       
        var result: [String: [String: String] ]  = [:]
        
        for v in variants{
            
            result[v.grp_label] = [:]
            
            for option in v.options{
                result[v.grp_label]![option.label] = String(option.value)
            }
        }
        
        return result
        
    }
    
    
    
    func get_payment_url(order_id: Int) {
    
        var parameters = [
            "order_id":String(order_id)
        ]
        
        let mOrderPaymentView = self.order_container.subviews[2] as! OrderPaymentView
        if let mp = mOrderPaymentView.selected_payment{
            parameters["payment"] = mp.id
        }
        
        if let sess = Session.getInstance(), let user = sess.user{
                parameters["user_id"] = "\(user.id)"
                parameters["user_token"] = "\(user.token)"
        }
        
        
       let api = SimpleRequestApi()
        
        Utils.printDebug("\(parameters)")
        
        MyProgress.show()
        
               api.run(url: OrderConstances.Api.API_GET_PAYMENT_URL, parameters: parameters) { (parser) in
                
                Utils.printDebug("\(parser)")
               
                
                if(parser?.success == 1){
                    
                    MyProgress.dismiss()
                    
                       
                    if ModuleManager.isEnabled(module: "order_payment"){
                        
                        let link: String = (parser?.result!.stringValue)!
                        self.startMakePaymentController(url: link)
                        
                    }

                    
                }else if(parser?.success == -1){

                     MyProgress.dismiss()
                    
                }
                   
            }
        
    }
    
    func startMakePaymentController(url: String) {
              
        let sb = UIStoryboard(name: "MakePaymentController", bundle: nil)
        let ms: MakePaymentController = sb.instantiateViewController(withIdentifier: "make_payment_VC") as! MakePaymentController
           
        ms.delegate = self
        ms.payment_link = url
        
        ms.modalPresentationStyle = .fullScreen
        self.present(ms, animated: true)
 
    }
    
    
    func done(controller: MakePaymentController) {
        
        controller.dismiss(animated: true)
        
        self.current_page = self.current_page+1
        self.total = 0
        self.next_page(title: "DONE".localized, page: self.current_page)
        
    }
       
    func failed(errors: [String : String], controller: MakePaymentController) {
          
        controller.dismiss(animated: true)
        self.showAlertError(title: "Payment Error!".localized, content: errors, msgBnt: "Dismiss".localized)
        
    }
       
}


extension UIViewController {
    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }

    @objc func dismissKeyboard() {
        view.endEditing(true)
    }
}



