/*
 CamerasListViewController.swift
 
 View controller for cameras list interface
 */

import UIKit
import XPMobileSDK

let kAllCamerasFolderId = "1926418B-893E-4AD6-A258-FB4A9AB57453"

class CamerasListViewController: UIViewController, XPMobileSDKConnectionDelegate, UITableViewDelegate, UITableViewDataSource {

    typealias ItemType = [String: Any]
    var camerasList:[ItemType]! = []
    
    @IBOutlet weak var tableView: UITableView!
    
    // MARK: Life cycle methods

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "Cameras List"
        XPMobileSDK.addDelegate(self)
        self.tableView.tableFooterView = UIView.init(frame: CGRect.zero)
        self.loadCameras()
    }
    
    // MARK: Fetch and parse cameras list methods
    
    /*
     */
    func loadCameras() {
        XPMobileSDK.getAllViewsAndCameras(withSuccessHandler: { (response) in
            let item = (response.responseItems![0] as! NSDictionary)["Items"] as? ItemType
            self.parseItem(item!)
            self.tableView.reloadData()
        }, failureHandler: { (error) in
            print("Error fetching all views and cameras")

        })
    }
    
    /*
     * Recursive method for filtering only cameras from response
     */
    func parseItem(_ item: ItemType) {
        var items:[ItemType] = []
        if (item["Item"] is NSDictionary) {
            //When there is only one item, then its type is NSDictionary, so to keep the consistency, we create an array of one item
            items = [item["Item"] as! ItemType]
        }
        else if (item["Item"] is NSArray) {
            //If the items are more than one, then they are an NSArray
            items = item["Item"] as! [ItemType]
        }
        
        for item in items {
            if (item["Type"] as! String == "Camera") {
                //When an item of type 'Camera' is found, it is appended to the list of cameras to be displayed
                camerasList.append(item)
            }
            else if (item["Type"] as! String == "Folder" && (item["Id"] as! String).caseInsensitiveCompare(kAllCamerasFolderId) == ComparisonResult.orderedSame) || (item["Type"] as! String == "View") {
                //When the item is of type 'Folder' with the View ID of 'All Cameras' or of type 'View',
                //Parse its child items
                parseItem(item["Items"] as! ItemType)
            }
        }
    }
    
    //MARK: UITableViewDataSource methods
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return camerasList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let simpleTableIdentifier = "CameraTableItem"
        var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: simpleTableIdentifier)
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: simpleTableIdentifier)
        }
        let cameraItem: ItemType? = camerasList[indexPath.row]
        cell?.textLabel?.text = cameraItem!["Name"] as? String
        return cell ?? UITableViewCell()
    }
    
    //MARK: UITableViewDelegate methods
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let camera = camerasList[indexPath.row]
        let sb = UIStoryboard(name: "Main", bundle: nil)
        let cameraPlaybackViewController = sb.instantiateViewController(withIdentifier: "CameraPlaybackViewController") as! CameraPlaybackViewController
        cameraPlaybackViewController.cameraID = camera["Id"] as! XPSDKViewID
        cameraPlaybackViewController.cameraName = camera["Name"] as! String
    
        navigationController?.pushViewController(cameraPlaybackViewController, animated: true)
    }

}
