//
//  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 PaymentSelectorController: MyUIViewController, EmptyLayoutDelegate, ErrorLayoutDelegate, MakePaymentControllerDelegate{
   

    var order: Order?
    //Declare User For Current Session
    var myUserSession: User? = nil
    var viewManager: LoaderViewManager =  LoaderViewManager()

    @IBOutlet weak var buttons_container: UIView!
    @IBOutlet weak var pay_now: UIButton!
   
    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var navigationBarItem: UINavigationItem!
    @IBOutlet weak var viewContainer: UIView!
    
    @IBAction func payAction(_ sender: Any) {
        
        
        if let _order = self.order{
            get_payment_url(order_id: _order.id)
        }
        
        
    }
    
   
    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 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{
            
        }
    }


    func setup_payment()  {
        
        pay_now.backgroundColor = Colors.primaryColor
        pay_now.setTitle("Pay now".localized, for: .normal)
        pay_now.setTitleColor(.white, for: .normal)
        pay_now.initItalicFont()

       
        self.mOrderPaymentView = UINib(nibName: "OrderPaymentView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! OrderPaymentView

        mOrderPaymentView!.viewController = self
        mOrderPaymentView!.setup()
        
        viewContainer.addSubview(mOrderPaymentView!)
        viewContainer.addConstraintsWithFormat(format: "H:|[v0]|", views: mOrderPaymentView!)
        viewContainer.addConstraintsWithFormat(format: "V:|[v0]|", views: mOrderPaymentView!)
        
        self.mOrderPaymentView!.isHidden = false
        
        mOrderPaymentView!.updateAmount(total: 100.0, currency: order?.items.first?.currency)
        
        view.layoutIfNeeded()
                      
    
    }
   
    override func viewDidLoad() {
        super.viewDidLoad()


        self.hideKeyboardWhenTappedAround()
        
        
        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()
        
        setup_payment()
       
    }
    
    
    
    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 = "Checkout".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) {
        
        
       
        
    }
    
    var mOrderPaymentView: OrderPaymentView?
    
    func get_payment_url(order_id: Int) {
    
        var parameters = [
            "order_id":String(order_id)
        ]
        

        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
               
                if(parser?.success == 1){
                    
                    MyProgress.dismiss()
                    
                    Utils.printDebug("\(parser)")
                        
                    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
        self.present(ms, animated: true)
 
    }
    
    
    func done(controller: MakePaymentController) {
        
        
        SwiftEventBus.post("payment_done")
        
        controller.dismiss(animated: true)
        
        let alert = UIAlertController(title: "Payment done!".localized, message: "Your payment was successful!".localized, preferredStyle: .alert)

        alert.addAction(UIAlertAction(title: "Dismiss".localized, style: .default, handler: { action in
            alert.dismiss(animated: true)
            self.dismiss(animated: true)
        }))

        self.present(alert, animated: true)
        
       
    }
       
    func failed(errors: [String : String], controller: MakePaymentController) {
          
        
         SwiftEventBus.post("payment_failed")
        
       controller.dismiss(animated: true)
        self.showAlertError(title: "Payment Error!".localized, content: errors, msgBnt: "Dismiss".localized)
        
    }
       
}





