//
//  VideoViewController.swift
//  kt
//
//  Created by neox on 28.09.17.
//  Copyright © 2017 SimpleCode. All rights reserved.
//

import UIKit

class VideoViewController: UIViewController {
    
    @IBOutlet weak var tableview: UITableView!
    
    var videoList : [VideoModel] = []
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        self.tableview.estimatedRowHeight = 44.0;
        self.tableview.rowHeight = UITableViewAutomaticDimension;
        self.tableview.separatorStyle = .None
        
        Facade.sharedInstance().getVideo({ (videoList: [VideoModel]) in
            self.videoList = videoList
            self.tableview.reloadData()
            }, onError: { (error: String) in
                AlertViewUtil.showErrorAlert(error, vc: self)
        }) {
            
        }
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return videoList.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! VideoTableViewCell
        cell.label.text = videoList[indexPath.row].label
        return cell
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let youtubeId = videoList[indexPath.row].youtube_id
        var youtubeUrl = NSURL(string:"youtube://\(youtubeId)")!
        if UIApplication.sharedApplication().canOpenURL(youtubeUrl){
            UIApplication.sharedApplication().openURL(youtubeUrl)
        } else{
            youtubeUrl = NSURL(string:"https://www.youtube.com/watch?v=\(youtubeId)")!
            UIApplication.sharedApplication().openURL(youtubeUrl)
        }
    }
}
