//
//  VideoPlayerViewController.swift
//  VideoPlayer
//
//  Created by Christian Leonhard Corsten on 27.01.16.
//  Copyright © 2016 Christian Corsten. All rights reserved.
//

import Foundation
import UIKit
import AVKit

class VideoPlayerViewController: AVPlayerViewController, AVPlayerViewControllerDelegate
{
    let channelLogoView = UIView(frame: CGRectMake(35, 35, 200, 80))
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        // add a channel logo on top of our AVPlayer View
        channelLogoView.addSubview(UIImageView(image: UIImage(named: "logo_ProSiebenHD_small")))
        channelLogoView.alpha = 0.5
        contentOverlayView?.addSubview(channelLogoView)
        
        // setup player item, player, and delegate
        // We used the following local file for for the demo during the lecture:
        // let playerItem = AVPlayerItem(URL: NSURL(string: "file:///Users/Chris/Movies/Movie.mp4")!)
        let playerItem = AVPlayerItem(URL: NSURL(string: "http://distribution.bbb3d.renderfarming.net/video/mp4/bbb_sunflower_1080p_30fps_normal.mp4")!)
        player = AVPlayer(playerItem: playerItem)
        delegate = self
        
        // add timings for interstitials
        let timeStart = CMTime(seconds: 167.9, preferredTimescale: 1)
        let timeDuration = CMTime(seconds: 21, preferredTimescale: 1)
        let timeRange = CMTimeRange(start: timeStart , duration: timeDuration)
        let interstitialTimeRage = AVInterstitialTimeRange(timeRange: timeRange)
        playerItem.interstitialTimeRanges = [interstitialTimeRage]
        
        // start playback
        player?.play()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func playerViewController(playerViewController: AVPlayerViewController,
                  willPresentInterstitialTimeRange interstitial: AVInterstitialTimeRange) {
        
        NSLog("Will play interstitial content!")
        
        // hide the channel logo
        contentOverlayView?.hidden = true
        
        // disable timeline scrubbing for the user
        self.requiresLinearPlayback = true
    }
    
    func playerViewController(playerViewController: AVPlayerViewController,
         didPresentInterstitialTimeRange interstitial: AVInterstitialTimeRange) {
        
        NSLog("Did play interstitial content!")
        
        // show the channel logo
        contentOverlayView?.hidden = false
        
        // enable timeline scrubbing for the user
        self.requiresLinearPlayback = false
    }
   
}

