//
//  LaunchScreenViewController.swift
//  Astro
//
//  Created by Jeremy Wiebe on 2016-11-04.
//  Copyright © 2016 Mobify Research & Development Inc. All rights reserved.
//

import Foundation

// Marker custom view for visual debugger
class LaunchScreenView: UIView {}

class LaunchScreenViewController: UIViewController {
    override func loadView() {
        let size = UIScreen.main.bounds.size
        self.view = LaunchScreenView(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))

        // Check if launch screen configured
        guard let launchScreenNibName = _mainBundle().infoDictionary?["UILaunchStoryboardName"] as? String else {
            AstroLog.logger(AstroLog.Application).info("Info.plist does not contain a " +
                "'UILaunchStoryboardName' key. Launch screen will not be extended. " +
                "Specify a launch screen in your application and call " +
                "`Application.dismissLaunchImage()` when the application is ready " +
                "for user interaction")
            return
        }

        // Try loading from xib first (compiled to .nib files)
        if let _ = _mainBundle().path(forResource: launchScreenNibName, ofType: "nib") {
            let topLevelObjects = _mainBundle().loadNibNamed(launchScreenNibName, owner: nil, options: nil)
            if let mainView = topLevelObjects?.first as? UIView {
                AstroLog.logger(AstroLog.Application).info("Found Launch Screen xib at \(launchScreenNibName).xib.  Extending launch screen.")
                mainView.translatesAutoresizingMaskIntoConstraints = false
                self.view.addSubview(mainView)
                mainView.pinToSuperviewEdges()
                return
            }
        }

        // Next try storyboard (compiled to .storyboardc files)
        if let _ = _mainBundle().path(forResource: launchScreenNibName, ofType: "storyboardc") {
            let storyboard = UIStoryboard(name: launchScreenNibName, bundle: _mainBundle())
            if let vc = storyboard.instantiateInitialViewController() {
                AstroLog.logger(AstroLog.Application).info("Found Launch Screen storyboard at \(launchScreenNibName).storyboard.  Extending launch screen.")

                vc.view.translatesAutoresizingMaskIntoConstraints = false
                vc.willMove(toParent: self)
                addChild(vc)
                view.addSubview(vc.view)
                vc.view.pinToSuperviewEdges()
                return
            }
        }
    }
}
