/*
 CamerasLiveViewController.m
 
 View controller for live video interface
 */

#import "CameraLiveViewController.h"

@import XPMobileSDK;

@interface CameraLiveViewController ()
@end

@implementation CameraLiveViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.cameraName;
    [self startCurrentCameraStream];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self closeStream];
}

- (void)applicationWillEnterForeground:(NSNotification *)notification
{
    [self startCurrentCameraStream];
}

- (void)applicationDidEnterBackground:(NSNotification *)notification
{
    [self closeStream];
}

- (void)startCurrentCameraStream {
    [XPMobileSDK requestStreamForCameraID:self.cameraID size:CGSizeMake(1920, 1440) method:XPSDKVideoConnectionMethodPush signal:XPSDKVideoConnectionSignalLive fps:8 compressionLevel:90 userInitiatedDownsampling:NO keyFramesOnly:NO resizeSupported:YES time:nil usesTranscoding:YES successHandler:^(XPSDKResponse * response, XPSDKVideoConnection * videoConnection) {
        XPSDKDownstreamVideoConnection *downstreamVideoConnection = (XPSDKDownstreamVideoConnection *)videoConnection;
        cameraVideoView = [[CameraVideoView alloc] initWithFrame:self.view.bounds];
        [cameraVideoView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];

        [self.view addSubview:cameraVideoView];
        [cameraVideoView setDelegate:self];
        cameraVideoView.videoConnection = downstreamVideoConnection;
        [cameraVideoView setLoadingIndicatorVisible:YES];
        downstreamVideoConnection.delegate = cameraVideoView;
        [downstreamVideoConnection open];
        
    } failureHandler:^(NSError * error) {
        
    }];
}

- (void)closeStream
{
    XPSDKVideoConnection *videoConnection = cameraVideoView.videoConnection;
    cameraVideoView.videoConnection = nil;
    if (videoConnection != nil) {
        [XPMobileSDK closeVideoConnectionWithVideoConnection:videoConnection successHandler:^(XPSDKResponse * response) {
            NSLog(@"Video connection closed");
        } failureHandler:^(NSError * error) {
            NSLog(@"Video connection close failed");
        }];
    }
    
}

#pragma mark camera video view delegate

- (void)cameraVideoViewReceivedFirstFrame: (CameraVideoView *) cameraVideoView { }

- (void)cameraVideoViewLostConnection:(CameraVideoView *)cameraVideoView { }

- (void)cameraVideoViewRestoredConnection:(CameraVideoView *)cameraVideoView { }

- (void)cameraVideoView:(CameraVideoView *)cameraVideoView changedRecordingState:(BOOL)newRecordingState { }

- (void)cameraVideoView:(CameraVideoView *)cameraVideoView changedMotionState:(BOOL) newMotionState { }

- (void)cameraVideoViewReceivedResolutionChange:(CameraVideoView *)cameraVideoView { }


@end
