//
//  AppDelegate.swift
//  iPOS
//
//  Created by BBC on 06/10/16.0//  Copyright © 2016 BBC. All rights reserved.
//

import UIKit
import GooglePlaces
import Firebase
import Crashlytics
import SumUpSDK

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    static var leftViewController: LeftViewController!
    static var firebase: FirebaseApp!

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        self.createMenuView()
        //settings.setSelectedPrinter() -- called after login
        //settings.setSelectedPrinterLabel() -- called after login
        //settings.getPrinterSerialNumber() //async call. -- called after login
        SumUpSDK.setup(withAPIKey: Util.getPropertyValue(key: "API_KEY_SUMUP"))
        
        //GMSPlacesClient.provideAPIKey(Util.getPropertyValue(key: "API_KEY_GOOGLEPLACES"))
        
        FirebaseApp.configure()
        //Fabric.with([Crashlytics.self]) -- replaced by firebase
        Util.writeLogCustom(eventName: "app_start", name: "AppDelagate", text: "Application started at \(Util.DateToFullDateString(date: Date()))")
        return true
    }
    
    fileprivate func createMenuView() {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        
        var startUpController: UIViewController!
        
        let loginViewController = storyboard.instantiateViewController(withIdentifier: "loginViewController") as! LoginViewController
        let contactsViewController = storyboard.instantiateViewController(withIdentifier: "contactsViewController") as! MasterViewController
        let splashScreenViewController = storyboard.instantiateViewController(withIdentifier: "splashScreenViewController") as! SplashScreenViewController
        let firstConfigurationViewController = storyboard.instantiateViewController(withIdentifier: "firstConfigurationViewController") as! FirstConfigurationViewController
        
        State.createSessionManager(dataSource: settings.DataServiceUrl)

        startUpController = splashScreenViewController
        
        if(self.isNewApp()){
            if settings.isDemoVersion{
                startUpController = loginViewController
                self.setStarUpMenu(storyboard: storyboard, startUpController: startUpController, contactsViewController: contactsViewController, loginViewController: loginViewController)
            }
            else{
                startUpController = firstConfigurationViewController
                self.setStarUpMenu(storyboard: storyboard, startUpController: startUpController, contactsViewController: contactsViewController, loginViewController: loginViewController)
            }
        }
        else{
            var username: String = ""
            var password: String = ""
            
            if let _username = settings.LoggedInUserName, let _password = settings.LoggedInUserPassword{
                username = _username
                password = _password
            }
            
            self.validateUser(username: username, password: password, wsCompletionHandler: {

                result in
                if result == false {
                    settings.LoggedInUserName = nil
                    settings.LoggedInUserId = nil
                    settings.LoggedInUserPassword = nil
                    startUpController = loginViewController
                    Util.writeLogLogin(method: "Login", success: false, customAttribute: ["User":"\(username)", "StoreId":"\(settings.StoreId)"])
                }
                else{
                    startUpController = contactsViewController
                    Util.writeLogLogin(method: "Login", success: true, customAttribute: ["User":"\(username)", "StoreId":"\(settings.StoreId)"])
                }
                
                self.setStarUpMenu(storyboard: storyboard, startUpController: startUpController, contactsViewController: contactsViewController, loginViewController: loginViewController)
                
                self.getWSVersion { result in
                    if self.checkWSVersion() == false{
                        let message = Util.getString("LoginVersionNotCompatible")
                        Util.GeneralAlert(viewController: startUpController, message: message)
                    }
                }
            })
            self.setStarUpMenu(storyboard: storyboard, startUpController: startUpController, contactsViewController: contactsViewController, loginViewController: loginViewController)
        }
    }
    
    func setStarUpMenu(storyboard: UIStoryboard, startUpController: UIViewController, contactsViewController: MasterViewController, loginViewController: LoginViewController){
        let leftViewController = storyboard.instantiateViewController(withIdentifier: "leftViewController") as! LeftViewController
        AppDelegate.leftViewController = leftViewController
        
        let nvc: UINavigationController = UINavigationController(rootViewController: startUpController)
        
        leftViewController.contactsViewController = nvc
        
        let slideMenuController = ExSlideMenuController(mainViewController:nvc, leftMenuViewController: leftViewController)
        slideMenuController.automaticallyAdjustsScrollViewInsets = true
        slideMenuController.delegate = contactsViewController
        self.window?.backgroundColor = UIColor(red: 236/255, green: 238/255, blue: 241/255, alpha: 1.0)
        self.window?.rootViewController = slideMenuController
        self.window?.makeKeyAndVisible()
    }
    
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
        Util.writeLogCustom(eventName: "app_background", name: "AppDelagate", text: "Application status background at \(Util.DateToFullDateString(date: Date()))")
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        Util.writeLogCustom(eventName: "app_end", name: "AppDelagate", text: "Application status inactive at \(Util.DateToFullDateString(date: Date()))")
    }

    func validateUser(username: String, password: String, wsCompletionHandler: @escaping(Bool) -> Void){
        var isValid: Bool = false
        State.validateUserCredentials(email: username, password: password, showActivityView: false) { response in
            
            if let response = response {
                if response.isUsernameOrPasswordInvalid{
                    isValid = false
                }
                else if response.isUsernameDisabled{
                    isValid = false
                }
                else if response.changePasswordOnFirstLogon{
                    isValid = false
                }
                else if password == ""{
                    isValid = false
                }
                else{
                    isValid = true
                }
                
                settings.userSettings = response
                
                if let ss = response.storeSetup{
                    settings.storeSetupSettings = ss
                    settings.setSelectedPrinter()
                    settings.setSelectedPrinterLabel() 
                    settings.getPrinterSerialNumber()
                    settings.getPrinterFirmwareVersion()
                    
                    Defaults.googleApiKey = settings.storeSetupSettings.apiKeyGooglePlaces
                    GMSPlacesClient.provideAPIKey(settings.storeSetupSettings.apiKeyGooglePlaces)
    
                }
            }
            wsCompletionHandler(isValid)
        }
    }
    
    func getWSVersion(wsCompletionHandler: @escaping(Bool) -> Void){
        State.getVersion(completionHandler: { result in
            wsCompletionHandler(result)
        })
    }
    
    func checkWSVersion() -> Bool{
        let appVersion: Util.Version = Util.Version(version: State.appVersionString)
        let wsVersion: Util.Version = Util.Version(version: State.wsVersionString)
        
        if State.wsVersionString == ""{
            return true
        }
        
        if wsVersion >= appVersion{
            return true
        }
        else{
            return false
        }
    }
    
    func isNewApp() -> Bool{
        guard settings.defaults.string(forKey: SettingsController.keys.ST_DATASERVICE) != nil else {
            guard settings.defaults.string(forKey: SettingsController.keys.ST_FISCALPRINTER) != nil else{
                guard settings.defaults.string(forKey: SettingsController.keys.ST_PRINTERTYPE) != nil else{
                    guard settings.defaults.string(forKey: SettingsController.keys.ST_STOREID) != nil else{
                        guard settings.defaults.string(forKey: SettingsController.keys.ST_PRINTERLABEL) != nil else{
                            return true
                        }
                        return false
                    }
                    return false
                }
                return false
            }
            return false
        }
        return false
    }
}
