//
//  AppDelegateSwift.swift
//  MCPlus
//
//  Created by seo ha on 13/02/2019.
//  Copyright © 2019 KangSH. All rights reserved.
//

import Foundation
import UIKit
import CoreData
import CoreNFC
import ReplayKit
import Fabric
import Crashlytics

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    fileprivate var obf:Obfuscator = Obfuscator(withSalt: ["mcareplus" as AnyObject])
    
    @available(iOS 10, *)
    var persistentContainer:NSPersistentContainer{
        // MARK: - Core Data stack
        let _persistentContainer = NSPersistentContainer(name: "MCPlus")
        _persistentContainer.loadPersistentStores { (storeDescription, error) in
            if error != nil{
                // Replace this implementation with code to handle the error appropriately.
                // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                
                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                abort()
            }
        }
        return _persistentContainer
    }
    
    var userDefaults:UserDefaults = UserDefaults.standard
    var resURL:String?
    
    enum ALERT_TAG:Int {
        case UPDATE = 1
        case CANCEL = 2
    }
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        Fabric.with([Crashlytics.self])
        
        self.versionCheck()
        
        
        if let nav = self.window?.rootViewController as? UINavigationController{
            nav.delegate = self
        }
        
        #if DEBUG
        
        #else
        //안티디버거
        disable_attach()
        #endif

        
        
        return true
    }
    
    
    
    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        if userActivity.activityType != NSUserActivityTypeBrowsingWeb{
            return false
        }
        
        // Confirm that the NSUserActivity object contains a valid NDEF message.
        if #available(iOS 12.0, *) {
            let ndefMessage = userActivity.ndefMessagePayload
            if ndefMessage.records.count <= 0 || ndefMessage.records.first?.typeNameFormat == NFCTypeNameFormat.empty {
                return false
            }
        }
        
        return true
    }
    
    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.
        if let cookies = HTTPCookieStorage.shared.cookies{
            let cookieData = NSKeyedArchiver.archivedData(withRootObject: cookies)
            self.userDefaults.set(cookieData, forKey: "Cookies")
        }
    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {
        
        self.versionCheck()
        
        //화면잠금 모드로 고고씽
        // 지문인식을 받기 위해 지문인식 창이 떴다가 다시 돌아오는 경우도 applicationDidBecomeActive: 함수가 호출된다
        
        let formatString = "yyyy-MM-dd hh:mm:ss"
        let now = Date()
        let savedTime = (self.userDefaults.object(forKey: "fingerprintAuthTime") as? String)?.fromDate(format: formatString)
        
        let diff = (savedTime?.timeIntervalSince(now) ?? 0) * -1
        
        if diff > 1 || savedTime == nil{
            do{
                guard let info = Bundle.main.infoDictionary else{ return }
                
                if info["LockScreenUse"] as? Bool == true{
                    let VC = ScreenLockViewController()
                    self.window?.rootViewController?.present(VC, animated: true, completion: nil)
                }
            }
        }
        
        // 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.
        if let cookiesData = self.userDefaults.object(forKey: "Cookies") as? Data{
            do{
                guard let cookies = NSKeyedUnarchiver.unarchiveObject(with: cookiesData) as? [HTTPCookie] else{ return }
                
                for cookie in cookies{
                    HTTPCookieStorage.shared.setCookie(cookie)
                }
            }
        }
        
    }
    
    func applicationWillTerminate(_ application: UIApplication) {
        if #available(iOS 10.0, *){
            saveContext()
        }
    }
}

extension AppDelegate{
    // MARK: - Core Data Saving support
    @available(iOS 10, *)
    func saveContext(){
        let context = persistentContainer.viewContext
        guard context.hasChanges == true else {
            do{
                try context.save()
            }catch{
                abort()
            }
            return
        }
    
    }
    
    func showAlertWithTag(tag:ALERT_TAG){
        
        switch tag {
        case .UPDATE:
            self.visibleViewController?.showAlert("", "version update alarm message".localized, "update".localized, "cancel".localized, { [weak self](action) in
                guard let res = self?.resURL, let url = URL(string: res) else{
                    exit(0)
                }
                
                if #available(iOS 10.0, *) {
                    
                    UIApplication.shared.open(url, options: [UIApplication.OpenExternalURLOptionsKey : Any](), completionHandler: nil)
                }else{
                    UIApplication.shared.openURL(url)
                }
                
                }, { [weak self](action) in
                    //취소 누름
                    self?.showAlertWithTag(tag: .CANCEL)
            })
            
        case .CANCEL:
            self.visibleViewController?.showAlert("", "update cancel alarm message".localized, "ok".localized, nil, { (action) in
                exit(0)
            })
        }
        
    }
    
    func versionCheck(){
        var param = [String:Any]()
        
        param["platformType"] = Constants.PLATFORM_TYPE
        param["appName"] = MCarePlusConstants.APP_NAME
        param["certType"] = MCarePlusConstants.CERT_TYPE
        
        APIClient("\(MCarePlusConstants.DOMAIN_NAME)\(MCarePlusConstants.APP_NAME)\(Constants.API_TYPE_VERSION_CHECK).json")
            .param(reqParam: param)
            .enType(.json)
            .connect { [weak self](result:[String:Any]) in
                
                guard let info = Bundle.main.infoDictionary, let currentVersionString = info["CFBundleShortVersionString"] as? String, let currentVersion = Float(currentVersionString) else{ return }
                
                let versionOrder = result["versionOrder"] as? Float ?? 0
                
                if versionOrder > currentVersion{
                    // 업데이트 필요
                    self?.resURL = result["marketUrl"] as? String
                    self?.showAlertWithTag(tag: .UPDATE)
                }else{
                    print("최신 버전이 설치되어 있음.")
                }
                self?.checkiOSRooting()
            }
    }

    //MARK: = RootingCheck
    func checkiOSRooting() {
        var rootingCheck:MCareMessageRequestProtocol!
        var crackCehck:TGfgWLPFSsedkMjVFwzECGIJlWLmXNHAProtocol!
        
        let number = Int.random(in: 1...5)
        switch number {
        case 1:
            rootingCheck = MCareMessageRequest5()
            crackCehck = TGfgWLPFSsedkMjVFwzECGIJlWLmXNHA1()
        case 2:
            rootingCheck = MCareMessageRequest4()
            crackCehck = TGfgWLPFSsedkMjVFwzECGIJlWLmXNHA2()
        case 3:
            rootingCheck = MCareMessageRequest3()
            crackCehck = TGfgWLPFSsedkMjVFwzECGIJlWLmXNHA3()
        case 4:
            rootingCheck = MCareMessageRequest2()
            crackCehck = TGfgWLPFSsedkMjVFwzECGIJlWLmXNHA4()
        case 5:
            rootingCheck = MCareMessageRequest1()
            crackCehck = TGfgWLPFSsedkMjVFwzECGIJlWLmXNHA5()
        default:
            break
        }
        
        //폰이 루팅 되어 있는지 체크한다.
        if rootingCheck.isMsgRequest() {
            let rootingMsg:String = NSLocalizedString("RootingWarnningMessage", comment: obf.reveal(key:[176, 206, 203, 140, 254, 224, 157, 227, 197, 159, 192, 219, 77, 143, 198, 242, 137, 235, 252, 152, 230, 197, 183, 202, 227, 65, 158, 240, 250, 128, 255, 198, 182, 208, 229, 136, 234, 214, 75]))
            let rootingTitle:String = NSLocalizedString("AlertTitleWarnning", comment: "경고")
            
            self.visibleViewController?.showAlert(rootingTitle, rootingMsg, "닫기")
            
            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                exit(0)
            }
        }
        
        let crackResult:String = crackCehck.RrSysWIEJNXJSjLdLYdkUhuSZCTsCzYc()
    
        //크랙 여부를 체크한다.
        if !(crackResult == CommonConstants.CRACK_CODE_1001) {
            var crackMsg:String = NSLocalizedString("CrackWarnningMessage", comment: obf.reveal(key:[183, 248, 210, 141, 239, 209, 80, 129, 244, 223, 182, 197, 244, 136, 241, 234, 137, 230, 216, 85, 159, 214, 255, 128, 245, 232, 159, 240, 208, 128, 253, 235, 125, 183, 250, 229, 141, 248, 208, 155, 231, 253, 152, 214, 255, 67]))
            crackMsg = crackMsg.appending("\n").appending(crackResult)
            let crackTitle:String = NSLocalizedString("AlertTitleWarnning", comment: "경고")
            
            self.visibleViewController?.showAlert(crackTitle, crackMsg, "닫기")
            
            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                exit(0)
            }
        }
    }
    
    
}

extension AppDelegate:UINavigationControllerDelegate{
    func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool){
        if navigationController.viewControllers.first == viewController{
            navigationController.navigationBar.isHidden = true
        }else{
            navigationController.navigationBar.isHidden = false
        }
    }
}
