import UIKit
import LocalAuthentication
import Async
import WowonderMessengerSDK
import Toast_Swift
import OneSignalFramework
import GoogleSignIn
import GoogleMaps
import GooglePlaces

class SplashScreenVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!
    @IBOutlet weak var showStack: UIStackView!
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.authenticateWithBiometrics()
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.initializeOneSignal()
        self.initializeGoogleFrameworks()
    }
    
    func authenticateWithBiometrics() {
        let context = LAContext()
        if isBiometricAuthenticationAvailable() {
            if UserDefaults.standard.getFingerprintLock(Key: Local.FINGERPRINT_LOCK.FingerprintLock) {
                context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: "Please Authorise Your App") { success, error in
                    DispatchQueue.main.async {
                        if let error = error as? LAError {
                            exit(0)
                        } else {
                            self.getSiteSetting()
                        }
                    }
                }
            } else {
                self.getSiteSetting()
            }
        } else {
            self.getSiteSetting()
        }
    }
    
    func isBiometricAuthenticationAvailable() -> Bool {
        var isBiometricAuthenticationAvailable = false
        var error: NSError? = nil
        if LAContext().canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: &error) {
            isBiometricAuthenticationAvailable = (error == nil)
        }
        return isBiometricAuthenticationAvailable
    }
    
    func initializeOneSignal() {
        OneSignal.Debug.setLogLevel(.LL_VERBOSE)
        OneSignal.initialize(AppInstance.instance.siteSetting?.ios_m_push_id ?? "", withLaunchOptions: appDelegate.launchOptions)
        OneSignal.Notifications.requestPermission({ accepted in
            print("User accepted notifications: \(accepted)")
        }, fallbackToSettings: true)
        OneSignal.User.pushSubscription.addObserver(appDelegate)
        if let currentPlayerId = OneSignal.User.pushSubscription.id {
            appDelegate.savePlayerId(currentPlayerId)
        }
    }
    
    private func initializeGoogleFrameworks() {
        let gidConfig = GIDConfiguration(clientID: AppInstance.instance.siteSetting?.googleAppId ?? "")
        GIDSignIn.sharedInstance.configuration = gidConfig
        GMSServices.provideAPIKey(AppInstance.instance.siteSetting?.google_map_api ?? "")
        GMSPlacesClient.provideAPIKey(AppInstance.instance.siteSetting?.google_map_api ?? "")
    }
    
}

// MARK: - Extensions

// MARK: Api Call
extension SplashScreenVC {
    
    private func getSiteSetting() {
        if Connectivity.isConnectedToNetwork() {
            self.showStack.isHidden = false
            self.activityIndicator.startAnimating()
            Async.background {
                GetSettingManager.sharedInstance.getSiteSetting(completionBlock: { (success, authError, serverError, error) in
                    Async.main {
                        if (success != nil) {
                            AppInstance.instance.siteSetting = success
                            AppInstance.instance.connectivity_setting = success?.connectivitySystem ?? ""
                            self.initialConfig()
                            let status = AppInstance.instance.getUserSession()
                            if status {
                                self.fetchUserProfile()
                            } else {
                                self.activityIndicator.stopAnimating()
                                self.showStack.isHidden = true
                                let newVC =  R.storyboard.main.signUpMainNav()
                                appDelegate.window?.rootViewController = newVC
                            }
                        } else if (authError != nil) {
                            self.activityIndicator.stopAnimating()
                            self.showStack.isHidden = true
                            print("sessionError = \(authError?.errors?.error_text ?? "")")
                        } else if (serverError != nil) {
                            self.activityIndicator.stopAnimating()
                            self.showStack.isHidden = true
                            print("serverError = \(serverError?.errors?.error_text ?? "")")
                        } else {
                            self.activityIndicator.stopAnimating()
                            self.showStack.isHidden = true
                            print("error = \(error?.localizedDescription ?? "")")
                        }
                    }
                })
            }
        } else {
            self.activityIndicator.stopAnimating()
            self.showStack.isHidden = true
            self.view.makeToast(InterNetError)
        }
    }
    
    private func fetchUserProfile() {
        if Connectivity.isConnectedToNetwork() {
            let userId = AppInstance.instance._userId
            let sessionId = AppInstance.instance._sessionId
            Async.background {
                GetUserDataManager.instance.getUserData(user_id: userId, session_Token: sessionId, fetch_type: API.Params.user_data) { (success, sessionError, serverError, error) in
                    Async.main {
                        self.activityIndicator.stopAnimating()
                        self.showStack.isHidden = true
                        if success != nil {
                            SocketHelper.shared.emit_join(username: AppInstance.instance.userProfile?.username ?? "", user_id: AppInstance.instance._userId)
                            AppInstance.instance.userProfile = success?.user_data ?? nil
                            AppInstance.instance.getDownloadMediaData()
                            if (OneSignal.User.externalId != AppInstance.instance.userProfile?.user_id ?? "") {
                                OneSignal.logout()
                                OneSignal.login(AppInstance.instance.userProfile?.user_id ?? "")
                            }
                            let newVC = R.storyboard.dashboard.tabBarNav()
                            appDelegate.window?.rootViewController = newVC
                        } else if sessionError != nil {
                            print("sessionError = \(sessionError?.errors?.error_text ?? "")")
                            self.view.makeToast(sessionError?.errors?.error_text)
                        } else if serverError != nil {
                            print("serverError = \(serverError?.errors?.error_text ?? "")")
                            self.view.makeToast(serverError?.errors?.error_text)
                        } else {
                            print("error = \(error?.localizedDescription ?? "")")
                            self.view.makeToast(error?.localizedDescription)
                        }
                    }
                }
            }
        } else {
            self.activityIndicator.stopAnimating()
            self.showStack.isHidden = true
            self.view.makeToast(InterNetError)
        }
    }
    
}
