import UIKit
import Async
import FBSDKLoginKit
import GoogleSignIn
import WowonderMessengerSDK
import AuthenticationServices
import Toast_Swift

class LoginVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var backButton: UIButton!
    @IBOutlet weak var versionLabel: UILabel!
    @IBOutlet weak var forgotPassBtn: UIButton!
    @IBOutlet weak var usernameTextFieldTF: UITextField!
    @IBOutlet weak var passwordTextFieldTF: UITextField!
    @IBOutlet weak var loginBtn: UIButton!
    @IBOutlet weak var signupBtn: UIButton!
    
    // MARK: - Properties
    
    var iconClick = true
    var isAddAccount = false
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.initialConfig()
    }
    
    // MARK: - Selectors
    
    // Back Button Action
    @IBAction func backButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.navigationController?.popViewController(animated: true)
    }
    
    // Password Toggle Button Action
    @IBAction func passwrodToggleButtonAction(_ sender: UIButton) {
        if iconClick {
            passwordTextFieldTF.isSecureTextEntry = false
            sender.setImage(UIImage(named: "ic_Show_Password"), for: .normal)
        } else {
            passwordTextFieldTF.isSecureTextEntry = true
            // sender.setImage(UIImage(named: "ic_hide_Password"), for: .normal)
            sender.setImage(UIImage(named: "visibility_off"), for: .normal)
        }
        iconClick = !iconClick
    }
    
    // LogIn With Apple Button Action
    @IBAction func logInWithAppleButtonAction(_ sender: UIButton) {
        let appleIDProvider = ASAuthorizationAppleIDProvider()
        let request = appleIDProvider.createRequest()
        request.requestedScopes = [.fullName, .email]
        let authorizationController = ASAuthorizationController(authorizationRequests: [request])
        authorizationController.delegate = self
        authorizationController.performRequests()
    }
    
    // LogIn With Google Button Action
    @IBAction func loginWithGoogleButtonAction(_ sender: UIButton) {
        GIDSignIn.sharedInstance.signIn(withPresenting: self) { signInResult, error in
            if error == nil {
                guard let signInResult = signInResult else { return }
                let user = signInResult.user
                let userId = user.userID
                let idToken = user.accessToken.tokenString
                print("user auth: ", idToken)
                let token = user.idToken?.tokenString ?? ""
                self.googleLogin(access_Token: token)
            } else {
                self.dismissProgressDialog {
                    print(error?.localizedDescription ?? "")
                }
            }
        }
    }
    
    // LogIn With FaceBook Button Action
    @IBAction func loginWithFacebookButtonAction(_ sender: UIButton) {
        self.facebookLogin()
    }
    
    // Forgot Password Button Action
    @IBAction func forgotPasswordButtonAction(_ sender: UIButton) {
        let vc = R.storyboard.main.forgetPasswordVC()
        self.navigationController?.pushViewController(vc!, animated: true)
    }
    
    // LogIn Button Action
    @IBAction func logInButtonAction(_ sender: UIButton) {
        self.dismissKeyboard()
        self.handleLoginButtonTap()
    }
    
    // SignUp Button Action
    @IBAction func signUpButtonAction(_ sender: UIButton) {
        let vc = R.storyboard.main.signUpVC()
        self.navigationController?.pushViewController(vc!, animated: true)
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.setUpUI()
        self.dismissKeyboard()
    }
    
    // SetUp UI
    func setUpUI() {
        self.backButton.isHidden = !self.isAddAccount
        self.usernameTextFieldTF.attributedPlaceholder = NSAttributedString(string: NSLocalizedString("Username", comment: ""), attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray])
        self.passwordTextFieldTF.attributedPlaceholder = NSAttributedString(string: NSLocalizedString("Password", comment: ""), attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray])
        /*self.versionLabel.text = NSLocalizedString("Login To WoWonder Messenger", comment: "")
         self.versionLabel.preferredMaxLayoutWidth = 500
         self.versionLabel.sizeToFit()*/
        self.forgotPassBtn.setTitle(NSLocalizedString("Forgot password?", comment: ""), for: .normal)
        self.loginBtn.setTitle(NSLocalizedString("Log in", comment: ""), for: .normal)
        self.loginBtn.backgroundColor = UIColor.accent
        self.signupBtn.setTitle(NSLocalizedString("Sign Up", comment: ""), for: .normal)
    }
    
    // Handle Login Button Tap
    private func handleLoginButtonTap() {
        if appDelegate.isInternetConnected {
            if self.usernameTextFieldTF.text?.isEmpty ?? false {
                let securityAlertVC = R.storyboard.main.securityPopupVC()
                securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                securityAlertVC?.errorText = NSLocalizedString("Please enter username.", comment: "Please enter username.")
                self.present(securityAlertVC!, animated: true, completion: nil)
            } else if self.passwordTextFieldTF.text?.isEmpty ?? false {
                let securityAlertVC = R.storyboard.main.securityPopupVC()
                securityAlertVC?.titleText = NSLocalizedString("Security", comment: "Security")
                securityAlertVC?.errorText = NSLocalizedString("Please enter username.", comment: "Please enter username.")
                self.present(securityAlertVC!, animated: true, completion: nil)
            } else {
                let username = self.usernameTextFieldTF.text ?? ""
                let password = self.passwordTextFieldTF.text ?? ""
                let deviceId = UserDefaults.standard.getDeviceId(Key: Local.DEVICE_ID.DeviceId)
                Async.background {
                    UserManager.instance.authenticateUser(UserName: username, Password: password, DeviceId: deviceId) { (success, sessionError, serverError, error) in
                        if success != nil {
                            Async.main {
                                self.dismissProgressDialog {
                                    if success?.access_token == nil {
                                        let vc = R.storyboard.main.twoFactorVerifyVC()
                                        vc?.userID = success?.user_id ?? ""
                                        self.navigationController?.pushViewController(vc!, animated: true)
                                    } else {
                                        let user_Session = success?.getStringAnyData() ?? ["":""]
                                        UserDefaults.standard.setUserSession(value: user_Session, ForKey: Local.USER_SESSION.User_Session)
                                        AppInstance.instance.fetchUserProfile { userData in
                                            var getSwitchAccountData = UserDefaults.standard.getSwitchAccountData(Key: "Switch_Account_Data")
                                            let data = try! JSONSerialization.data(withJSONObject: getSwitchAccountData, options: [])
                                            let switchAccountData = try! JSONDecoder().decode([UserData].self, from: data)
                                            if switchAccountData.contains(where: { $0.user_id == userData?.user_data?.user_id }) {
                                                print("Switch Account Data Already Added")
                                            } else {
                                                var user = userData?.user_data?.getStringAnyData() ?? [:]
                                                user["access_token"] = success?.access_token
                                                getSwitchAccountData.append(user)
                                                UserDefaults.standard.setSwitchAccountData(value: getSwitchAccountData, ForKey: "Switch_Account_Data")
                                                print("Switch Account Data Added")
                                            }
                                        }
                                        let vc = R.storyboard.main.introVC()
                                        self.navigationController?.pushViewController(vc!, animated: true)
                                        self.view.makeToast(NSLocalizedString("Login Successfull!!", comment: "Login Successfull!!"))
                                    }
                                }
                            }
                        } else if sessionError != nil {
                            Async.main {
                                self.dismissProgressDialog {
                                    let securityAlertVC = R.storyboard.main.securityPopupVC()
                                    securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                                    securityAlertVC?.errorText = sessionError?.errors?.error_text ?? ""
                                    self.present(securityAlertVC!, animated: true, completion: nil)
                                }
                            }
                        } else if serverError != nil {
                            Async.main {
                                self.dismissProgressDialog {
                                    let securityAlertVC = R.storyboard.main.securityPopupVC()
                                    securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                                    securityAlertVC?.errorText = sessionError?.errors?.error_text ?? ""
                                    self.present(securityAlertVC!, animated: true, completion: nil)
                                }
                            }
                        } else {
                            Async.main {
                                self.dismissProgressDialog {
                                    let securityAlertVC = R.storyboard.main.securityPopupVC()
                                    securityAlertVC?.titleText = NSLocalizedString("Security", comment: "Security")
                                    securityAlertVC?.errorText = error?.localizedDescription ?? ""
                                    self.present(securityAlertVC!, animated: true, completion: nil)
                                }
                            }
                        }
                    }
                }
            }
        } else {
            self.dismissProgressDialog {
                let securityAlertVC = R.storyboard.main.securityPopupVC()
                securityAlertVC?.titleText  = NSLocalizedString("Internet Error", comment: "Internet Error")
                securityAlertVC?.errorText = InterNetError
                self.present(securityAlertVC!, animated: true, completion: nil)
            }
        }
    }
    
    private func facebookLogin() {
        if Connectivity.isConnectedToNetwork() {
            let fbLoginManager : LoginManager = LoginManager()
            fbLoginManager.logIn(permissions: ["email"], from: self) { (result, error) in
                if (error == nil) {
                    let fbloginresult : LoginManagerLoginResult = result!
                    if (result?.isCancelled)! {
                        self.dismissProgressDialog {
                        }
                        return
                    }
                    if !fbloginresult.grantedPermissions.isEmpty {
                        if fbloginresult.grantedPermissions.contains("email") {
                            if AccessToken.current != nil {
                                GraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completion: { (connection, result, error) -> Void in
                                    if error == nil {
                                        let dict = result as! [String : AnyObject]
                                        print("result = \(dict)")
                                        guard let firstName = dict["first_name"] as? String else { return }
                                        guard let lastName = dict["last_name"] as? String else { return }
                                        guard let email = dict["email"] as? String else { return }
                                        let accessToken = AccessToken.current?.tokenString
                                        Async.background {
                                            UserManager.instance.socialLogin(Provider: "facebook", AccessToken: accessToken ?? "", GoogleApiKey: "", completionBlock: { (success, sessionError, serverError, error) in
                                                if success != nil {
                                                    Async.main {
                                                        self.dismissProgressDialog {
                                                            let user_Session = success?.getStringAnyData() ?? ["":""]
                                                            UserDefaults.standard.setUserSession(value: user_Session, ForKey: Local.USER_SESSION.User_Session)
                                                            AppInstance.instance.fetchUserProfile { userData in
                                                                var getSwitchAccountData = UserDefaults.standard.getSwitchAccountData(Key: "Switch_Account_Data")
                                                                let data = try! JSONSerialization.data(withJSONObject: getSwitchAccountData, options: [])
                                                                let switchAccountData = try! JSONDecoder().decode([UserData].self, from: data)
                                                                if switchAccountData.contains(where: { $0.user_id == userData?.user_data?.user_id }) {
                                                                    print("Switch Account Data Already Added")
                                                                } else {
                                                                    var user = userData?.user_data?.getStringAnyData() ?? [:]
                                                                    user["access_token"] = success?.access_token
                                                                    getSwitchAccountData.append(user)
                                                                    UserDefaults.standard.setSwitchAccountData(value: getSwitchAccountData, ForKey: "Switch_Account_Data")
                                                                    print("Switch Account Data Added")
                                                                }
                                                            }
                                                            let vc = R.storyboard.main.introVC()
                                                            self.navigationController?.pushViewController(vc!, animated: true)
                                                            self.view.makeToast(NSLocalizedString("Login Successfull!!", comment: "Login Successfull!!"))
                                                        }
                                                    }
                                                } else if sessionError != nil {
                                                    Async.main {
                                                        self.dismissProgressDialog {
                                                            let securityAlertVC = R.storyboard.main.securityPopupVC()
                                                            securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                                                            securityAlertVC?.errorText = sessionError?.errors?.error_text ?? ""
                                                            self.present(securityAlertVC!, animated: true, completion: nil)
                                                        }
                                                    }
                                                } else if serverError != nil {
                                                    Async.main {
                                                        self.dismissProgressDialog {
                                                            let securityAlertVC = R.storyboard.main.securityPopupVC()
                                                            securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                                                            securityAlertVC?.errorText = sessionError?.errors?.error_text ?? ""
                                                            self.present(securityAlertVC!, animated: true, completion: nil)
                                                        }
                                                    }
                                                } else {
                                                    Async.main {
                                                        self.dismissProgressDialog {
                                                            let securityAlertVC = R.storyboard.main.securityPopupVC()
                                                            securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                                                            securityAlertVC?.errorText = error?.localizedDescription ?? ""
                                                            self.present(securityAlertVC!, animated: true, completion: nil)
                                                        }
                                                    }
                                                }
                                            })
                                        }
                                    }
                                })
                            }
                        }
                    }
                }
            }
        } else {
            self.dismissProgressDialog {
                let securityAlertVC = R.storyboard.main.securityPopupVC()
                securityAlertVC?.titleText  = NSLocalizedString("Internet Error", comment: "Internet Error")
                securityAlertVC?.errorText = InterNetError
                self.present(securityAlertVC!, animated: true, completion: nil)
                print("internetError - \(InterNetError)")
            }
        }
    }
    
    private func googleLogin(access_Token: String){
        if Connectivity.isConnectedToNetwork() {
            Async.background {
                UserManager.instance.socialLogin(Provider: "google", AccessToken: access_Token, GoogleApiKey: ControlSettings.googleApiKey, completionBlock: { (success, sessionError, serverError,error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                let user_Session = success?.getStringAnyData() ?? ["":""]
                                UserDefaults.standard.setUserSession(value: user_Session, ForKey: Local.USER_SESSION.User_Session)
                                AppInstance.instance.fetchUserProfile { userData in
                                    var getSwitchAccountData = UserDefaults.standard.getSwitchAccountData(Key: "Switch_Account_Data")
                                    let data = try! JSONSerialization.data(withJSONObject: getSwitchAccountData, options: [])
                                    let switchAccountData = try! JSONDecoder().decode([UserData].self, from: data)
                                    if switchAccountData.contains(where: { $0.user_id == userData?.user_data?.user_id }) {
                                        print("Switch Account Data Already Added")
                                    } else {
                                        var user = userData?.user_data?.getStringAnyData() ?? [:]
                                        user["access_token"] = success?.access_token
                                        getSwitchAccountData.append(user)
                                        UserDefaults.standard.setSwitchAccountData(value: getSwitchAccountData, ForKey: "Switch_Account_Data")
                                        print("Switch Account Data Added")
                                    }
                                }
                                let vc = R.storyboard.main.introVC()
                                self.navigationController?.pushViewController(vc!, animated: true)
                                self.view.makeToast(NSLocalizedString("Login Successfull!!", comment: "Login Successfull!!"))
                            }
                        }
                    } else if sessionError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                print("session Error = \(sessionError?.errors?.error_text ?? "")")
                                let securityAlertVC = R.storyboard.main.securityPopupVC()
                                securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                                securityAlertVC?.errorText = sessionError?.errors?.error_text ?? ""
                                self.present(securityAlertVC!, animated: true, completion: nil)
                            }
                        }
                    } else if serverError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                print("serverError = \(serverError?.errors?.error_text ?? "")")
                                let securityAlertVC = R.storyboard.main.securityPopupVC()
                                securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                                securityAlertVC?.errorText = sessionError?.errors?.error_text ?? ""
                                self.present(securityAlertVC!, animated: true, completion: nil)
                            }
                        }
                    } else {
                        Async.main {
                            self.dismissProgressDialog {
                                print("error = \(error?.localizedDescription ?? "")")
                                let securityAlertVC = R.storyboard.main.securityPopupVC()
                                securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                                securityAlertVC?.errorText = error?.localizedDescription ?? ""
                                self.present(securityAlertVC!, animated: true, completion: nil)
                            }
                        }
                    }
                })
            }
        } else {
            self.dismissProgressDialog {
                let securityAlertVC = R.storyboard.main.securityPopupVC()
                securityAlertVC?.titleText  = NSLocalizedString("Internet Error", comment: "Internet Error")
                securityAlertVC?.errorText = InterNetError
                self.present(securityAlertVC!, animated: true, completion: nil)
                print("internetError - \(InterNetError)")
            }
        }
    }
    
    private func appleLogin(access_Token: String){
        if Connectivity.isConnectedToNetwork() {
            Async.background {
                UserManager.instance.socialLogin(Provider: "apple", AccessToken: access_Token, GoogleApiKey: "", completionBlock: { (success, sessionError, serverError,error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                let user_Session = success?.getStringAnyData() ?? ["":""]
                                UserDefaults.standard.setUserSession(value: user_Session, ForKey: Local.USER_SESSION.User_Session)
                                AppInstance.instance.fetchUserProfile { userData in
                                    var getSwitchAccountData = UserDefaults.standard.getSwitchAccountData(Key: "Switch_Account_Data")
                                    let data = try! JSONSerialization.data(withJSONObject: getSwitchAccountData, options: [])
                                    let switchAccountData = try! JSONDecoder().decode([UserData].self, from: data)
                                    if switchAccountData.contains(where: { $0.user_id == userData?.user_data?.user_id }) {
                                        print("Switch Account Data Already Added")
                                    } else {
                                        var user = userData?.user_data?.getStringAnyData() ?? [:]
                                        user["access_token"] = success?.access_token
                                        getSwitchAccountData.append(user)
                                        UserDefaults.standard.setSwitchAccountData(value: getSwitchAccountData, ForKey: "Switch_Account_Data")
                                        print("Switch Account Data Added")
                                    }
                                }
                                let vc = R.storyboard.main.introVC()
                                self.navigationController?.pushViewController(vc!, animated: true)
                                self.view.makeToast(NSLocalizedString("Login Successfull!!", comment: "Login Successfull!!"))
                            }
                        }
                    } else if sessionError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                print("session Error = \(sessionError?.errors?.error_text ?? "")")
                                let securityAlertVC = R.storyboard.main.securityPopupVC()
                                securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                                securityAlertVC?.errorText = sessionError?.errors?.error_text ?? ""
                                self.present(securityAlertVC!, animated: true, completion: nil)
                            }
                        }
                    } else if serverError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                print("serverError = \(serverError?.errors?.error_text ?? "")")
                                let securityAlertVC = R.storyboard.main.securityPopupVC()
                                securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                                securityAlertVC?.errorText = sessionError?.errors?.error_text ?? ""
                                self.present(securityAlertVC!, animated: true, completion: nil)
                            }
                        }
                    } else {
                        Async.main {
                            self.dismissProgressDialog {
                                print("error = \(error?.localizedDescription ?? "")")
                                let securityAlertVC = R.storyboard.main.securityPopupVC()
                                securityAlertVC?.titleText  = NSLocalizedString("Security", comment: "Security")
                                securityAlertVC?.errorText = error?.localizedDescription ?? ""
                                self.present(securityAlertVC!, animated: true, completion: nil)
                            }
                        }
                    }
                })
            }
        } else {
            self.dismissProgressDialog {
                let securityAlertVC = R.storyboard.main.securityPopupVC()
                securityAlertVC?.titleText  = NSLocalizedString("Internet Error", comment: "Internet Error")
                securityAlertVC?.errorText = InterNetError
                self.present(securityAlertVC!, animated: true, completion: nil)
                print("internetError - \(InterNetError)")
            }
        }
    }
    
}

// MARK: - Extensions

// MARK: ASAuthorizationControllerDelegate Methods
extension LoginVC: ASAuthorizationControllerDelegate {
    
    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if let appleIDCredential = authorization.credential as?  ASAuthorizationAppleIDCredential {
            let userIdentifier = appleIDCredential.authorizationCode
            let fullName = appleIDCredential.fullName
            let email = appleIDCredential.email
            let authorizationCode = String(data: appleIDCredential.identityToken!, encoding: .utf8)!
            print("authorizationCode: \(authorizationCode)")
            self.appleLogin(access_Token: authorizationCode)
            print("User id is \(userIdentifier ?? Data()) \n Full Name is \(fullName?.givenName ?? "") \n Email id is \(email ?? "")")
        }
    }
    
    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        print("Error sign in with apple")
    }
    
}
