//
//  AppDelegate.swift
//  kt
//
//  Created by Alexandr Zalutskiy on 15.01.15.
//  Copyright (c) 2015 Alexandr Zalutskiy. All rights reserved.
//

import UIKit
import Fabric
import Crashlytics
import MessageUI
import XCGLogger
import Google

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, MFMailComposeViewControllerDelegate {
    
    var window: UIWindow?
    
    //  let splitDelegate = SplitDelegate()
    
    //  func getDocsDir() -> NSURL? {
    //    let fm = NSFileManager.defaultManager()
    //    fm.contentsAtPath("")
    //    return fm.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last
    //  }
    
    static func clearTempFolder(path: String) {
        let fileManager = NSFileManager.defaultManager()
        //    let tempFolderPath = NSTemporaryDirectory()
        do {
            //      let filePaths = try fileManager.contentsOfDirectoryAtPath(path)
            //      for filePath in filePaths {
            let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as NSURL
            let fileUrl = documentsUrl.URLByAppendingPathComponent("console.log")
            if fileManager.isDeletableFileAtPath(fileUrl!.absoluteString!) {
                try fileManager.removeItemAtPath("console.log")
            }
            //      }
        } catch {
            print("Could not clear temp folder: \(error)")
        }
    }
    
    func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
        debugPrint("willFinishLaunchingWithOptions begin")
        //  	Fabric.with([Crashlytics()])
        //    AppDelegate.clearTempFolder("console.log")
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.tokenExpired), name: TokenExpiredNotification, object: nil)
        projectSettings()
        CitiesManager.sharedInstance().loadCities()
        
        Facade.sharedInstance().getCities()
        Facade.sharedInstance().getCity(1)
        //    let sendLogsButton = UIButton(frame: CGRect(x: 150, y: 300, width: 150, height: 50))
        //    sendLogsButton.addTarget(self, action: #selector(AppDelegate.sendEmailButtonTapped), forControlEvents: .TouchUpInside)
        //    self.window!.rootViewController!.view.addSubview(sendLogsButton)
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        
        //    let vc = LoginViewController(nibName: nil, bundle: nil)
        
        if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
            //        window?.rootViewController = vc
            window?.rootViewController = storyboard.instantiateViewControllerWithIdentifier("iPhoneRootViewController")
        }  else {
            let vc = storyboard.instantiateViewControllerWithIdentifier("iPadRootViewController") as? UISplitViewController
            vc?.presentsWithGesture = false
            //      vc?.delegate = splitDelegate
            window?.rootViewController = vc
        }
        
        window?.makeKeyAndVisible()
        debugPrint("willFinishLaunchingWithOptions end")
        return true
    }
    
    func tokenExpired() {
        print("Token Expired. Resend Logging")
        Facade.sharedInstance().login(UserManager.sharedInstance().rLogin, password: UserManager.sharedInstance().rPassword, loginType: Facade.LoginType(rawValue: UserManager.sharedInstance().rLoginType)!, onSuccess: {
            print("Relogging Success")
            
            }, onError: { (error) in
                print("Relogging Failure")
                
                if let wd = self.window {
                    var vc = wd.rootViewController
                    if(vc is UINavigationController){
                        vc = (vc as! UINavigationController).visibleViewController
                    }
                    if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
                        vc!.navigationController?.popToRootViewControllerAnimated(false)
                    } else {
                        let loginVC = vc!.storyboard!.instantiateViewControllerWithIdentifier("iPhoneRootViewController") as? UINavigationController
                        vc!.presentViewController(loginVC!, animated: false, completion: { () -> Void in
                            if let pvc = self.window!.rootViewController as? UISplitViewController {
                                if let rvc = pvc.viewControllers[1] as? RootViewController {
                                    let homeVC = vc!.storyboard!.instantiateViewControllerWithIdentifier(CabinetControllerId)
                                    rvc.presentCenterViewController(homeVC, animated: false)
                                }
                            }
                        })
                    }
                    
                }
                
                
        }) {
            
        }
        /*
         let alert = UIAlertController(title: LS("token_has_expired"), message: nil, preferredStyle: .Alert)
         alert.addAction(UIAlertAction(title: LS("close"), style: .Cancel, handler: {(alertAction) in
         if let wd = self.window {
         var vc = wd.rootViewController
         if(vc is UINavigationController){
         vc = (vc as! UINavigationController).visibleViewController
         }
         if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
         vc!.navigationController?.popToRootViewControllerAnimated(false)
         } else {
         let loginVC = vc!.storyboard!.instantiateViewControllerWithIdentifier("iPhoneRootViewController") as? UINavigationController
         vc!.presentViewController(loginVC!, animated: false, completion: { () -> Void in
         if let pvc = self.window!.rootViewController as? UISplitViewController {
         if let rvc = pvc.viewControllers[1] as? RootViewController {
         let homeVC = vc!.storyboard!.instantiateViewControllerWithIdentifier(CabinetControllerId)
         rvc.presentCenterViewController(homeVC, animated: false)
         }
         }
         })
         }
         
         }
         }))
         window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)*/
    }
    
    func sendEmailButtonTapped(vc: UIViewController? = nil) {
        let mailComposeViewController = configuredMailComposeViewController()
        
        if MFMailComposeViewController.canSendMail() {
            if let vc = vc {
                vc.presentViewController(mailComposeViewController, animated: true, completion: nil)
            } else {
                self.window!.rootViewController!.presentViewController(mailComposeViewController, animated: true, completion: {
                    
                })
            }
        } else {
            self.showSendMailErrorAlert()
        }
    }
    
    func showSendMailErrorAlert() {
        let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail.  Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK")
        sendMailErrorAlert.show()
    }
    
    func configuredMailComposeViewController() -> MFMailComposeViewController {
        let mailComposerVC = MFMailComposeViewController()
        mailComposerVC.mailComposeDelegate = self // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property
        let file = "file.txt" //this is the file. we will write to and read from it
        
        let text = "some text" //just a text
        
        let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as NSURL
        
        let logFileData = NSData(contentsOfURL: AppDelegate.getMyLogPath())
        
        let now = NSDate()
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy/MM/dd' 'HH:mm:ss'"
        formatter.timeZone = NSTimeZone.localTimeZone()
        
        let message: String = ""
        
        mailComposerVC.setToRecipients(["assylkhan.rakhatov@gmail.com", "assylkhan.rakhatov@mail.ru"])
        mailComposerVC.setSubject(": " + formatter.stringFromDate(now))
        mailComposerVC.setMessageBody(message, isHTML: false)
        mailComposerVC.addAttachmentData(logFileData!, mimeType: "log", fileName: "console.log")
        //    mailComposerVC.addAttachmentData(imageData, mimeType: "image/png", fileName: "ImageName")
        
        return mailComposerVC
    }
    
    func exceptionLog() {
        NSSetUncaughtExceptionHandler({ exception in
            
            let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as NSURL
            let destinationUrl = documentsUrl.URLByAppendingPathComponent("console.log")
            NSLog("Exception Got \(exception.description)")
            AppDelegate.clearTempFolder("console.log")
            
            let text = "some text" //just a text
            
            //      NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"myfile.txt"];
            
            
            let filePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first!.stringByAppendingString("console.log")
            do {
                try exception.description.writeToFile(filePath, atomically: true, encoding: NSStringEncoding.init())
            } catch {
                print("could not")
            }
            
            
            //do what ever you what here
            //can save any `bool` so that as aaplication  run on immediate next launching of crash
            //could intimate any thing
            NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isExceptionOccured")
            //  [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isExceptionOccured"];
            
            
        })
        //    uncaughtExceptionHandler
        //    EDIT:
        if NSUserDefaults.standardUserDefaults().boolForKey("isExceptionOccured") {
            //call sever code here
            
            NSUserDefaults.standardUserDefaults().setBool(false, forKey: "isExceptionOccured")
            //      [[NSUserDefaults standardUserDefaults] setBool:FALSE forKey:@"isExceptionOccured"];
        }
    }
    
    static func getMyLogPath() -> NSURL {
        let cacheDirectory: NSURL = {
            let urls = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask)
            return urls[urls.endIndex - 1]
        }()
        let logPath: NSURL = cacheDirectory.URLByAppendingPathComponent("console.log")!
        return logPath
    }
    
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        //    exceptionLog()
        
        //UINavigationBar.appearance().barTintColor = UIColor(red: 234.0/255.0, green: 46.0/255.0, blue: 73.0/255.0, alpha: 1.0)
        UINavigationBar.appearance().tintColor = UIColor.whiteColor()
        UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()]
        
        //UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default)
        UINavigationBar.appearance().shadowImage = UIImage()
        UINavigationBar.appearance().barTintColor = Color.DashboardBlueColor
        //UINavigationBar.appearance().barStyle = UIBarStyle.Default
        //UINavigationBar.appearance().titleTextAttributes = nil
        //UINavigationBar.appearance().tintColor = .whiteColor()
        //UINavigationBar.appearance().setBottomBorderColor(UIColor.whiteColor(), height: 0)
        UINavigationBar.appearance().translucent = false
        //UINavigationBar.appearance().tintColor = UIColor.whiteColor()
        
        // Настройка счетчика на основе данных файла GoogleService-Info.plist.
        
        
        // [START tracker_swift]
        // Configure tracker from GoogleService-Info.plist.
        var configureError: NSError?
        GGLContext.sharedInstance().configureWithError(&configureError)
        assert(configureError == nil, "Error configuring Google services: \(configureError)")
        
        // Optional: configure GAI options.
        let gai = GAI.sharedInstance()
        gai.trackUncaughtExceptions = true  // report uncaught exceptions
        //gai.logger.logLevel = GAILogLevel.Verbose // remove before app release
        // [END tracker_swift]
        
        
        let log = XCGLogger.defaultInstance()
        
        
        log.setup(.Debug, showThreadName: true, showLogLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: AppDelegate.getMyLogPath(), fileLogLevel: .Debug)
        //    log.addLogDestination(XCGFileLogDestination(owner: log, writeToFile: "console.log", identifier: "advancedLogger.fileLogDestination", shouldAppend: true, appendMarker: "-- Relauched App --"))
        //    AppDelegate.redirectConsoleLogToDocumentFolder()
        Fabric.with([Crashlytics.self])
        return true
    }
    
    func uncaughtExceptionHandler(exception: NSException) {
        
        
        NSLog("Exception Got \(exception.description)")
        //do what ever you what here
        //can save any `bool` so that as aaplication  run on immediate next launching of crash
        //could intimate any thing
        NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isExceptionOccured")
        //  [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isExceptionOccured"];
        
    }
    
    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 throttle down OpenGL ES frame rates. 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.
    }
    
    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive 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.
        NSNotificationCenter.defaultCenter().postNotificationName(Notification.appDidBecomeActive, object: nil)
    }
    
    func applicationWillTerminate(application: UIApplication) {
        NSNotificationCenter.defaultCenter().removeObserver(self)
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    
    func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
        if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
            return UIInterfaceOrientationMask.Portrait
        }
        else {
            return [UIInterfaceOrientationMask.Portrait, UIInterfaceOrientationMask.LandscapeRight,
                    UIInterfaceOrientationMask.LandscapeLeft]
        }
    }
    
    func projectSettings() {
        let locationManager = LocationManager.sharedInstance()
        if NSUserDefaults.standardUserDefaults().valueForKey("first_opened") == nil {
            NSUserDefaults.standardUserDefaults().setBool(true, forKey: "first_opened")
        }
        AppLocalization.initialize()
        
        if NSUserDefaults.standardUserDefaults().objectForKey(UserDefaultsCity) == nil {
            NSUserDefaults.standardUserDefaults().setInteger(1, forKey: UserDefaultsCity)
            //TODO: uncomment when api fix
            locationManager.needGetUserCity = true
        }
        
        var path = NSSearchPathForDirectoriesInDomains(
            .DocumentDirectory,
            NSSearchPathDomainMask.UserDomainMask,
            true
            )[0] as String
        path += "/cities.plist"
        
        if !NSFileManager.defaultManager().fileExistsAtPath(path) {
            do {
                try NSFileManager.defaultManager().copyItemAtPath(
                    NSBundle.mainBundle().pathForResource("cities", ofType: "plist")!,
                    toPath: path
                )
            } catch _ {
                print("Cannot copy file!")
            }
        }
        
    }
}

// MFMailComposeViewControllerDelegate
extension AppDelegate {
    func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
        
        debugPrint("mailComposeController didFinishWithResult begin")
        switch (result) {
        case MFMailComposeResult.Cancelled:
            break
            
        case MFMailComposeResult.Saved:
            
            
            break
            
        case MFMailComposeResult.Sent:
            print("MFMailComposeResultSent")
            let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as NSURL
            let destinationUrl = documentsUrl.URLByAppendingPathComponent("console.log")
            do {
                try NSFileManager.defaultManager().removeItemAtURL(destinationUrl!)
            } catch {
                print(error)
            }
            break
            
        case MFMailComposeResult.Failed:
            print("MFMailComposeResultFailed")
            break
            
        default:
            break
        }
        
        //Dismiss the mailViewController.
        
        self.window!.rootViewController!.dismissViewControllerAnimated(true, completion: nil)
        debugPrint("mailComposeController didFinishWithResult end")
    }
}
