//
//  SignUpMainVC.swift
//  WoWonder
//
//  Created by iMac on 20/06/23.
//  Copyright © 2023 ScriptSun. All rights reserved.
//

import Foundation
import UIKit
import AuthenticationServices
import Async
import FBSDKLoginKit
import GoogleSignIn
import WowonderMessengerSDK

class SignUpMainVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var backButton: UIButton!
    @IBOutlet weak var loginBtn: UIButton!
    @IBOutlet weak var signupBtn: UIButton!
    @IBOutlet weak var signupLabel: UILabel!
    @IBOutlet weak var signupWithGoogleBtn: UIButton!
    @IBOutlet weak var signupWithGoogleLabel: UILabel!
    @IBOutlet weak var signupWithFacebookBtn: UIButton!
    @IBOutlet weak var signupWithFacebookLabel: UILabel!
    @IBOutlet weak var signupWithAppleBtn: UIButton!
    @IBOutlet weak var signupWithAppleLabel: UILabel!
    @IBOutlet weak var alreadyhaveanAccountLabel: UILabel!
    
    // MARK: - Properties
    
    var isAddAccount = false
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    
    // MARK: - Selectors
    
    // Back Button Action
    @IBAction func backButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.navigationController?.popViewController(animated: true)
    }
    
    @IBAction func loginWithApplePressed(_ sender: Any) {
        let appleIDProvider = ASAuthorizationAppleIDProvider()
        let request = appleIDProvider.createRequest()
        request.requestedScopes = [.fullName, .email]
        let authorizationController = ASAuthorizationController(authorizationRequests: [request])
        authorizationController.delegate = self
        authorizationController.performRequests()
    }
    
    @IBAction func signupBtnPressed(_ sender: Any) {
        let vc = R.storyboard.main.signUpVC()
        self.navigationController?.pushViewController(vc!, animated: true)
    }
    
    @IBAction func loginBtnPressed(_ sender: Any) {
        let vc = R.storyboard.main.loginVC()
        vc?.isAddAccount = self.isAddAccount
        self.navigationController?.pushViewController(vc!, animated: true)
    }
    
    @IBAction func googlePressed(_ sender: Any) {
        GIDSignIn.sharedInstance.signIn(withPresenting: self) { signInResult, error in
            if error == nil {
                guard let signInResult = signInResult else { return }
                let user = signInResult.user
                let token = user.idToken?.tokenString ?? ""
                self.googleLogin(access_Token: token)
            } else {
                self.dismissProgressDialog {
                    print(error?.localizedDescription ?? "")
                }
            }
        }
    }
    
    @IBAction func facebookPressed(_ sender: Any) {
        self.facebookLogin()
    }
    
    // MARK: - Helper Functions
    
    func setupUI() {
        self.backButton.isHidden = !self.isAddAccount
        self.loginBtn.setTitle(NSLocalizedString("Login", comment: ""), for: .normal)
        self.signupLabel.text = NSLocalizedString("Sign Up with Email", comment: "")
        self.signupWithGoogleLabel.text = NSLocalizedString("Sign Up with Google", comment: "")
        self.signupWithFacebookLabel.text = NSLocalizedString("Sign Up with Facebook", comment: "")
        self.signupWithAppleLabel.text = NSLocalizedString("Sign Up with Apple", comment: "")
        self.alreadyhaveanAccountLabel.text = NSLocalizedString("Already have an account?", comment: "")
    }
    
    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.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)")
            }
        }
    }
}

extension SignUpMainVC: 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) \n Full Name is \(String(describing: fullName)) \n Email id is \(String(describing: email))")
        }
    }
    
    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        print("error >>>>> ", error.localizedDescription)
    }
    
}
