//
//  AppDelegate.swift
//  JSONCreator
//
//  Created by Scott Pfeil on 8/2/19.
//  Copyright © 2019 Verizon Wireless. All rights reserved.
//

import UIKit
import MVMCoreUI
import VDS

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
    
    var window: UIWindow?
    var splitViewController: UISplitViewController?
    var mvcNav: UINavigationController?
    var dvcNav: UINavigationController?
    var mvc: UIViewController?
    var dvc: UIViewController?
    
    func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        // Setup our core object with the default implementation
        CoreUIObject.sharedInstance()?.defaultInitialSetup()
        return true
    }
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        // Override point for customization after application launch.
        splitViewController = window!.rootViewController as? UISplitViewController
        NavigationHandler.shared().viewControllerToPresentOn = splitViewController
        mvcNav = splitViewController?.viewControllers[0] as? UINavigationController
        mvcNav?.delegate = self
        mvc = mvcNav?.topViewController
        dvcNav = splitViewController?.viewControllers[splitViewController!.viewControllers.count-1] as? UINavigationController
        dvc = dvcNav?.topViewController
        dvc?.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
        dvc?.navigationItem.leftItemsSupplementBackButton = true
        splitViewController?.delegate = self
        splitViewController?.preferredDisplayMode = .allVisible
        
        let gr = UILongPressGestureRecognizer(target: self, action: #selector(jsonPasteAndGo))
        splitViewController?.view.addGestureRecognizer(gr)
        
        NotificationCenter.default.addObserver(forName: UIViewController.showDetailTargetDidChangeNotification, object: splitViewController, queue: nil) { [weak self] (notification) in
            if let strongSelf = self, let svc = notification.object as? UISplitViewController {
                if svc.isCollapsed {
                    strongSelf.mvc?.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Editor", style: .plain, target: self, action: #selector(self?.showEditor))
                } else {
                    strongSelf.mvcNav?.setViewControllers([strongSelf.mvc!], animated: false)
                    strongSelf.mvc?.navigationItem.rightBarButtonItem = nil
                }
            }
        }
        return true
    }
    
    @objc func jsonPasteAndGo(_ sender: UILongPressGestureRecognizer) {
        if sender.state == .ended {
            (dvc as? DetailViewController)?.textView.text = UIPasteboard.general.string
            (dvc as? DetailViewController)?.play()
        }
    }
    
    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.
    }
    
    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:.
    }
    
    // MARK: - Split view
    
    func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewControlller:UIViewController, onto primaryViewController:UIViewController) -> Bool {
        //guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
        //guard let _ = secondaryAsNavController.topViewController as? DetailViewController else { return false }
        return true
    }
    
    @objc func showEditor() {
        mvcNav?.pushViewController(dvc!, animated: true)
    }
}

extension AppDelegate: UINavigationControllerDelegate {
    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        if mvc == viewController {
            dvcNav?.setViewControllers([dvc!], animated: false)
        }
    }
}
