//
//  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


import FirebaseCore
import FirebaseAuth
import GoogleSignIn
import FBSDKLoginKit
import AuthenticationServices

protocol LoginOTPDelegate {
    func loginSuccess(controller: OtpViewController, user: User)
    func loginFaild(controller: OtpViewController)
}

class OtpViewController: MyUIViewController, UITextFieldDelegate {
    
  
  
    override func viewDidDisappear(_ animated: Bool) {
        //finish progress popup
        MyProgress.dismiss()
    }
    
  
    

    var phoneNumber: String?
    var delegate: LoginOTPDelegate? = nil
    
    var request: Int = 0

    override func viewWillDisappear(_ animated: Bool) {
        if let _ = self.navigationController, config.customToolbar == true{
            ////controller.navigationBar.isHidden = false
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        if let _ = self.navigationController, config.customToolbar == true{
            //controller.navigationBar.isHidden = true
        }
    }
    
    
    static func listner(parent: UIViewController) {
        
        SwiftEventBus.onMainThread(self, name: "open_view_login") { result in
            let sb = UIStoryboard(name: "Login", bundle: nil)
            if sb.instantiateInitialViewController() != nil {
                let ms: LoginViewController = sb.instantiateViewController(withIdentifier: "loginVC") as! LoginViewController
                parent.present(ms, animated: true, completion: nil)
            }
            
        }
    }
    
    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var navigationBarItem: UINavigationItem!
    @IBOutlet weak var stackView: UIStackView!
    @IBOutlet weak var view_container: EXUIView!
    @IBOutlet weak var otpPhoneField: SkyFloatingLabelTextField!
    @IBOutlet weak var otpCodeField: SkyFloatingLabelTextField!
    @IBOutlet weak var otpContainerVerify: UIStackView!
    @IBOutlet weak var sendCodeBtn: CustomButton!
    @IBOutlet weak var verifyCodeBtn: CustomButton!
    @IBOutlet weak var messageSentCodeLabel: UILabel!
    
    @IBAction func sendCodeAction(_ sender: Any) {
        
        guard let telephoneValue = otpPhoneField.text else {
            return
        }
        
        var parameters = [
            "telephone": telephoneValue
        ]
    
        if let sess = Session.getInstance(), let user = sess.user{
            parameters["userId"] = "\(user.id)"
        }
        
        let api = SimpleRequestApi()
         
         Utils.printDebug("\(parameters)")
         
         MyProgress.show()
         
        api.run(url: Constances.Api.API_OTP_SEND_CODE, parameters: parameters) { (parser) in
            
            
            if(parser?.success == 1){
                
                self.messageSentCodeLabel.text = "An SMS containing the code has been sent to your number %s. you can send again after 20s".localized.format(arguments: telephoneValue)
                self.sendCodeBtn.isHidden = true
                self.otpPhoneField.isEnabled = false
                
                
                //RESET SENDING CODE AFTER 10S
                DispatchQueue.main.asyncAfter(deadline: .now()+20) {
                    self.sendCodeBtn.isHidden = false
                    self.otpPhoneField.isEnabled = true
                }
                
                self.otpContainerVerify.isHidden = false
            }else if(parser?.success == 0){
                self.showAlert(title: "Error!".localized, content: (parser?.errors)!, msgBnt: "OK".localized)
            }
            
            MyProgress.dismiss()
        }
        
    }
    
    @IBAction func verifyCodeAction(_ sender: Any) {
        
        guard let telephoneValue = otpPhoneField.text else {
            return
        }
        
        guard let codeValue = otpCodeField.text else {
            return
        }
        
        var parameters = [
            "telephone": String(telephoneValue),
            "otpCode": String(codeValue),
        ]
    
        if let sess = Session.getInstance(), let user = sess.user{
            parameters["userId"] = "\(user.id)"
        }
        
        let api = UserLoader()
         
         Utils.printDebug("\(parameters)")
         MyProgress.show()
         
        api.run(url: Constances.Api.API_OTP_VERIFFY_CODE, parameters: parameters) { (userParser) in
            
            Utils.printDebug("\(userParser)")
            
            guard let parser = userParser else {
                return
            }
            
            if(parser.success == 1){
            
                let users = parser.parse()
                if users.count == 0{
                    let _ = Session.logout()
                }else{
                    Utils.printDebug("\(users[0])")
                           
                    if users[0].status == -1{
                        Session.logout()
                    }else{
                        
                        //save user in the database & session
                        Session.createSession(user: users[0])
                        
                        if let del = self.delegate{
                            del.loginSuccess(controller: self, user: users[0])
                        }
                        
                    }
                }
                
            }else{
                self.showErros(messages: parser.errors!)
            }
            
            MyProgress.dismiss()
        }
        
    }
    
    func loginWithPhone() {
        
       
        
    }
    
    @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 = "OTP".localized
        
        navigationBarItem.titleView = topBarTitle
        
    }
    

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = Colors.darkColor
        self.view_container.addShadowView()
        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()
        
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: UIResponder.keyboardWillHideNotification, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: UIResponder.keyboardWillShowNotification, object: nil)
        
        SwiftEventBus.onMainThread(self, name: "on_close_it") { result in
            
            if let _ = result?.object{
                
                if let mySession = Session.getInstance(), let user = mySession.user{
                    SwiftEventBus.post("on_main_refresh", sender: user)
                    self.dismiss(animated: true)
                }
            }
            
        }
      
    }
    
    
    @objc func handleKeyboardNotification(notification: NSNotification) {
        
        
        if let userInfo = notification.userInfo {
            
            let keyboardFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
            let isKeyboardShowing = notification.name == UIResponder.keyboardWillShowNotification
            
            
            if let textField = self.lastTextField, let _ = textField.superview?.convert(textField.frame, to: nil) {
                
                if isKeyboardShowing{
                    // so increase contentView's height by keyboard height
                    //self.constraintScrollBottomHeight.constant = keyboardFrame.height
                    UIView.animate(withDuration: 0, delay: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
                        self.view.layoutIfNeeded()
                    })
                    
                }else{
                    // so increase contentView's height by keyboard height
                    //self.constraintScrollBottomHeight.constant = 0
                    UIView.animate(withDuration: 0, delay: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
                        self.view.layoutIfNeeded()
                    })
                    
                }
                
            }
        
        }
    
    }
    
    
    var lastTextField: UITextField? = nil
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        lastTextField = textField
    }
    

    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        lastTextField = textField
        return true
    }
    
    func startMainVC() {
        
        let sb = UIStoryboard(name: "Main", bundle: nil)
        if let vc = sb.instantiateInitialViewController() {
            self.present(vc, animated: true)
        }
        
    }
    
    
    func keyboardDismiss() {
        self.view.endEditing(true)
    }
    
   
    func setupViews() {
        
        otpPhoneField.delegate = self
        otpCodeField.delegate = self
        
        otpContainerVerify.isHidden = true
       
        otpPhoneField.textColor = UIColor.black
        otpPhoneField.lineColor = UIColor.gray
        otpPhoneField.selectedTitleColor = UIColor.black
        otpPhoneField.selectedLineColor = Colors.primaryColor
        otpPhoneField.selectedLineHeight = 1.5
        otpPhoneField.lineHeight = 0.5
        otpPhoneField.titleColor = Colors.primaryColor
        otpPhoneField.font = UIFont(name: AppConfig.Design.Fonts.regular, size: otpPhoneField.font!.pointSize)
        otpPhoneField.titleFont = UIFont(name: AppConfig.Design.Fonts.regular, size: otpCodeField.font!.pointSize)!
        
        otpCodeField.keyboardType = .default
        otpCodeField.textColor = UIColor.black
        otpCodeField.lineColor = UIColor.gray
        otpCodeField.selectedTitleColor = UIColor.black
        otpCodeField.selectedLineColor = Colors.primaryColor
        otpCodeField.selectedLineHeight = 1.5
        otpCodeField.lineHeight = 0.5
        otpCodeField.titleColor = Colors.primaryColor
        otpCodeField.font = UIFont(name: AppConfig.Design.Fonts.regular, size: otpPhoneField.font!.pointSize)
        otpCodeField.titleFont = UIFont(name: AppConfig.Design.Fonts.regular, size: otpCodeField.font!.pointSize)!
        
        otpPhoneField.placeholder = "Enter phone number".localized
        otpCodeField.placeholder = "Enter received code".localized
    
        messageSentCodeLabel.textAlignment = .center
        messageSentCodeLabel.initDefaultFont(size: 14)
        messageSentCodeLabel.textColor = .gray
        
        sendCodeBtn.setTitle("Send code".localized.uppercased(), for: .normal)
        verifyCodeBtn.setTitle("Verify code".localized.uppercased(), for: .normal)
        
        otpPhoneField.delegate = self
        otpCodeField.delegate = self
        
        
        if let phone = phoneNumber{
            self.otpPhoneField.text = phone
        }
        
        
        if let sess = Session.getInstance(), let user = sess.user{
            self.otpPhoneField.text = user.phone
        }
    }

    
    func showErros(messages: [String: String]) {
        
         self.showAlertError(title: "Error",content: messages,msgBnt: "OK")
        
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }


}




