/*
 LoginViewController.swift
 
 View controller for login interface
 */

import UIKit
import XPMobileSDK

class LoginViewController: UIViewController, XPMobileSDKConnectionDelegate  {
    @IBOutlet weak var address: UITextField!
    @IBOutlet weak var port: UITextField!
    @IBOutlet weak var username: UITextField!
    @IBOutlet weak var password: UITextField!
    let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    
    // MARK: Life cycle methods
    
    override func viewDidLoad() {
        super.viewDidLoad()
        XPMobileSDK.addDelegate(self)
        self.title = "Mobile SDK Playback Video Sample"
        self.port.text = "8081"        
        activityIndicator.center = CGPoint(x: view.bounds.size.width/2, y: view.bounds.size.height/2)
        self.view.addSubview(activityIndicator)
    }

    //MARK: IBActions
    
    /**
     * Connect and login to server
     */
    @IBAction func login(_ sender: Any) {
        let serverInfo = XPSDKServerInfo.init(host: address.text!, port: (Int(port.text!) as NSNumber?)!)
        activityIndicator.startAnimating()
        XPMobileSDK.connectAndLoginForServerInfo(serverInfo, username: self.username.text!, password: self.password.text!, shouldSave: false, successHandler: { (response) in
            self.activityIndicator.stopAnimating()
            XPMobileSDK.removeDelegate(self)
            self.performSegue(withIdentifier: "goToCameras", sender: sender)
        }, failureHandler: { (error) in
            self.activityIndicator.stopAnimating()
            self.alert(withTitle: "Error", message: "Unable to login")
        })
    }
    
    /**
     * Display application name & version number
     */
    @IBAction func about(_ sender: Any) {
        alert(withTitle: "About", message: "Milestone SDK Live Video Sample\nFor more information visit www.milestonesys.com.")
    }
    
    //MARK: Helper methods
    
    /**
     * Helper method for presenting an alert controller
     - Parameters:
     - title: Title displayed in the alert dialog
     - message: Message displayed in the alert dialog
     */
    func alert(withTitle title:String, message:String) {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let defaultAction = UIAlertAction(title: "OK", style: .default, handler: {(_ action: UIAlertAction) -> Void in
        })
        alertController.addAction(defaultAction)
        present(alertController, animated: true) {() -> Void in }
    }
    
    //MARK: XPMobileSDKConnectionDelegate methods
    
    func connectionDidFailConnectWithError(_ error: NSError) {
        self.alert(withTitle: "Error", message: "Unable to connect")
    }

    func connectionCodeError(_ connection: XPSDKConnection) {
        self.alert(withTitle: "Error", message: "Unable to connect")
    }

}

