/*
 CameraPlaybackViewController.swift
 
 View controller for video playback interface
 */

import UIKit
import XPMobileSDK

class CameraPlaybackViewController: UIViewController, CameraVideoViewDelegate {
    enum CameraPlaybackPlaying : Int {
        case None = 0
        case Forward = 1
        case Backwards = -1
    }
    
    var cameraID:XPSDKViewID!
    var cameraName:String!
    var cameraVideoView:CameraVideoView!
    var playing:CameraPlaybackPlaying = CameraPlaybackPlaying.None
    var playSpeed:Float = 1.0
    
    // MARK: Life cycle methods
    
    override func viewDidLoad() {
        super.viewDidLoad()
        startCurrentCameraStream()
        title = cameraName;
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        closeStream()
    }
    
    func applicationWillEnterForeground(_ notification: Notification) {
        startCurrentCameraStream()
    }
    
    func applicationDidEnterBackground(_ notification: Notification) {
        closeStream()
    }
    
    // MARK: Video Stream methods

    func startCurrentCameraStream() {
        XPMobileSDK.requestStream(forCameraID: cameraID, size: CGSize(width: 1920, height: 1440), method: XPSDKVideoConnectionMethodPush, signal: XPSDKVideoConnectionSignalPlayback, fps: 8, compressionLevel: 90, userInitiatedDownsampling: false, keyFramesOnly: false, resizeSupported: true, time: NSDate(), usesTranscoding: true, successHandler: {(_ response: XPSDKResponse, _ videoConnection: XPSDKVideoConnection) -> Void in
            let downstreamVideoConnection = videoConnection as? XPSDKDownstreamVideoConnection
            let videoViewFrame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height - 44)
            self.cameraVideoView = CameraVideoView(frame: videoViewFrame)
            self.cameraVideoView!.autoresizingMask = [.flexibleWidth, .flexibleHeight]
            self.view.addSubview(self.cameraVideoView!)
            self.cameraVideoView!.delegate = self
            self.cameraVideoView!.videoConnection = downstreamVideoConnection
            downstreamVideoConnection!.delegate = self.cameraVideoView!
            downstreamVideoConnection!.open()
        }, failureHandler: {(error:NSError!) in
            
        })
    }
    
    func closeStream() {
        let videoConnection: XPSDKVideoConnection? = cameraVideoView.videoConnection
        cameraVideoView.videoConnection = nil
        if videoConnection != nil {
            XPMobileSDK.closeVideoConnection(videoConnection: videoConnection!, successHandler: { (_ response: XPSDKResponse!) in
                print("Video connection closed")
            }, failureHandler: {(error:NSError!) in
                print("Error closing video connection")
            })
        }
    }
    
    //MARK: IBActions
    
    @IBAction func backwards(_ sender: Any) {
        if playing == CameraPlaybackPlaying.Backwards {
            return
        }
        else {
            playing = CameraPlaybackPlaying.Backwards
            XPMobileSDK.changeStream(forVideoID: self.cameraVideoView!.videoConnection!.videoID, playSpeed: -playSpeed, successHandler: { (_ response: XPSDKResponse!) in

            }, failureHandler: { (_ error: NSError!) in

            })
            self.cameraVideoView!.isLoadingIndicatorVisible = true
        }
    }
    
    @IBAction func pause(_ sender: Any) {
        playing = CameraPlaybackPlaying.None;
        XPMobileSDK.changeStream(forVideoID: self.cameraVideoView!.videoConnection!.videoID, playSpeed: 0, successHandler: { (_ response: XPSDKResponse!) in

        }, failureHandler: { (_ error: NSError!) in
            
        })
    }
    
    @IBAction func forward(_ sender: Any) {
        if playing == CameraPlaybackPlaying.Forward {
            return
        }
        else {
            playing = CameraPlaybackPlaying.Forward
            XPMobileSDK.changeStream(forVideoID: self.cameraVideoView!.videoConnection!.videoID, playSpeed: playSpeed, successHandler: { (_ response: XPSDKResponse!) in
                
            }, failureHandler: { (_ error: NSError!) in
                
            })
            self.cameraVideoView!.isLoadingIndicatorVisible = true
        }
    }
    
    //MARK: CameraVideoViewDelegate methods
    
    func cameraVideoViewReceivedFirstFrame(_ cameraVideoView: CameraVideoView) {}
    
    func cameraVideoViewLostConnection(_ cameraVideoView: CameraVideoView) {
        cameraVideoView.showErrorMessage("Connection lost")
    }
    
    func cameraVideoViewRestoredConnection(_ cameraVideoView: CameraVideoView) {}
    
    func cameraVideoViewReceivedResolutionChange(_ cameraVideoView: CameraVideoView) {}
    
    func cameraVideoViewDatabaseStartReached(_ cameraVideoView: CameraVideoView) {}
    
    func cameraVideoViewDatabaseEndReached(_ cameraVideoView: CameraVideoView) {}
    
    func cameraVideoViewDatabaseError(_ cameraVideoView: CameraVideoView) {}
    
    func cameraVideoViewReceivedSegment(_ cameraVideoView: CameraVideoView) {}
}
