//
//  LoginViewController.swift
//  NearbyStores
//
//  Created by DT Team on 5/20/18.
//  Copyright © DT Team. All rights reserved.
//

import UIKit
import SwiftEventBus
import SkyFloatingLabelTextField
import SwiftWebVC



class UserQRCodeController: MyUIViewController {
   
    static func newInstance() -> UserQRCodeController{
        let str = UIStoryboard(name: "UserQRCode", bundle: nil)
        let vc: UserQRCodeController = str.instantiateViewController(withIdentifier: "qrVC") as! UserQRCodeController
        return vc
    }

    var request: Int = 0
    override func viewWillDisappear(_ animated: Bool) {
        if let _ = self.navigationController, config.customToolbar == true{
            ////controller.navigationBar.isHidden = false
            MyProgress.dismiss()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        if let _ = self.navigationController, config.customToolbar == true{
            //controller.navigationBar.isHidden = true
        }
    }
    
    
    @IBOutlet weak var qrCodeImage: UIImageView!
    @IBOutlet weak var bottomMessage: UILabel!
    @IBOutlet weak var topMessage: UILabel!
    @IBOutlet weak var navigationBarItem: UINavigationItem!
    @IBOutlet weak var navigationBar: UINavigationBar!
    
    
    @objc func onBackHandler()  {
        
        if let controller = self.navigationController{
            //controller.navigationBar.isHidden = true
            controller.popViewController(animated: true)
            ////controller.navigationBar.isHidden = false
        }else{
            self.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: .ionicons(.iosArrowForward), size: CGSize(width: 30, height: 30), textColor: Colors.darkColor)
        }else{
            arrowImage = UIImage.init(icon: .ionicons(.iosArrowBack), size: CGSize(width: 30, height: 30), textColor: Colors.darkColor)
        }
        
        
        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 = []
      
        
        if(config.backHome ==  true){
            navigationBarItem.leftBarButtonItems?.append(customBarButtonItem)
        }
        
        
    }
    
   
    
    let topBarTitle: EdgeLabel = {
        
        let titleLabel = EdgeLabel()
        
        titleLabel.text = ""
        titleLabel.textColor = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.primaryColor)
        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 = "QR Code".localized
        
        navigationBarItem.titleView = topBarTitle
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
     
        self.navigationController?.navigationBar.isHidden = true
        
        if config.customToolbar{
            
            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()
            setupNavBarButtons()
            
        }else{
            self.navigationBar.isHidden = true
        }
       
    
        if !config.customToolbar{
            self.navigationBar.isHidden = true
        }
        

        setupViews()
        
      
    }
    
    
  
    private static var userToken: String = ""
    private static var userId: Int = 0
    
  
   
    func setupViews() {
        
        
        self.topMessage.initBolodFont(size: 18)
        self.bottomMessage.initItalicFont()
        
        guard let sess = Session.getInstance(), let user = sess.user else{
            return
        }
        
        self.topMessage.text = "Hello, %@\nHere is your Qr code".localized.format(arguments: user.name)
        self.bottomMessage.text = "Scan to check the profile".localized
     
    
        if user.id != UserQRCodeController.userId && UserQRCodeController.userToken == ""{
            self.loadQrCodeFromApi()
        }else{
            let qr = self.generateQRCode(from: "profile:\(UserQRCodeController.userToken)")
            self.qrCodeImage.image = qr
            self.qrCodeImage.layer.magnificationFilter = CALayerContentsFilter.nearest
        }
        
    }
    
    
    func loadQrCodeFromApi(){
        
      /*  guard let sess = Session.getInstance(), let user = sess.user else{
            return
        }
        
        MyProgress.show()
        
        var parameters = [
            "user_id": String(user.id),
        ]
        
        let api =  SimpleLoader()
        api.run(url: Constances.Api.API_GENERATE_QRCODE_TOKEN, parameters: parameters) { parser in
             
            MyProgress.dismiss()
            
            if let p = parser, let re = p.result, p.success == 1{
                let qr = self.generateQRCode(from: "profile:\(re.stringValue)")
                self.qrCodeImage.image = qr
                self.qrCodeImage.layer.magnificationFilter = CALayerContentsFilter.nearest
            }else{
                self.showAlert(title: "Error".localized, content: ["err" : "Something went wrong".localized], msgBnt: "OK".localized)
            }
           
            
        }*/
        
    }

    
    func generateQRCode(from string: String) -> UIImage? {
        let data = string.data(using: String.Encoding.ascii)
        if let QRFilter = CIFilter(name: "CIQRCodeGenerator") {
            QRFilter.setValue(data, forKey: "inputMessage")
            guard let QRImage = QRFilter.outputImage else {return nil}
            let imgViewQR = UIImage(ciImage: QRImage)
            return imgViewQR
        }
        return nil
    }


}




