//
//  AppDelegate.swift
//  TVML – Hello World & TED Talks Viewer
//
//  Created by Krishna Subramanian on 03/02/16.
//  Copyright © 2016 Krishna Subramanian. All rights reserved.
//

import UIKit
import TVMLKit

// TVApplicationControllerDelegate allows you to observe and manage different states of a TVApplicationController object
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, TVApplicationControllerDelegate {
  
  var window: UIWindow?
  
  // TVApplicationController is a centralized controller that links event handling (JS) to UI, navigation stack, and storage (tvOS)
  var appController: TVApplicationController?
  
  // Path to server
  static let serverPath = "http://localhost:9001/"
  
  // Path to JavaScript code
  static let scriptPath = "\(AppDelegate.serverPath)js/app.js"
  
  // App is ready to run
  func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
    window = UIWindow(frame: UIScreen.mainScreen().bounds)
    
    // An object that is used to initialize TVApplicationController
    let appControllerContext = TVApplicationControllerContext()
    
    // Fill the context with URL to JavaScript code and URL to server (where the content resides)
    guard let javaScriptURL = NSURL(string: AppDelegate.scriptPath) else {
      print("unable to create NSURL")
      return false
    }
    
    appControllerContext.javaScriptApplicationURL = javaScriptURL
    
    // Passed to the onLaunch() function in the JavaScript code (accessible as options.BASEURL)
    appControllerContext.launchOptions["BASEURL"] = AppDelegate.serverPath
    
    // Start the TVApplicationController with the given context, in the given window, and with the given delegate
    appController = TVApplicationController(context: appControllerContext, window: window, delegate: self)
    
    return true
  }
  
}
