var streaming = false;
var video;
var cameraStream;
var width = 320;
var height;

async function activateCamera ( field )
{
    sendCommand ( 'getCameraAccess' , { } , function ( data ) 
    {
        if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' || data.errnum !== 0 )
        {
            return;
        }
        if ( streaming )
        {
            if ( typeof cameraStream != 'undefined' )
            {
                cameraStream.getTracks().forEach ( function ( track )
                {
                    track.stop();
                } );
                cameraStream = undefined;
            }
            jQuery ( 'div#initiated div#content section.new-claim div#div_' + streaming + ' video#video' ).remove();
            jQuery ( 'div#initiated div#content section.new-claim div#div_' + streaming + ' canvas#canvas' ).remove();
            jQuery ( 'div#initiated div#content section.new-claim form div#div_' + streaming + ' p a.take_picture' ).hide();
            jQuery ( 'div#initiated div#content section.new-claim form div#div_' + streaming + ' p a.activate_camera' ).show();
            streaming = false;
        }
        jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name + ' p a.activate_camera' ).before ( '<video id="video"></video>' );
        jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name + ' p a.activate_camera' ).hide();
        video = jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name + ' p video#video' )[0];
        video.addEventListener ( 'canplay' , function ( ev )
            {
                if (!streaming) {
                    height = video.videoHeight / (video.videoWidth/width);
                
                    // Firefox currently has a bug where the height can't be read from
                    // the video, so we will make assumptions if this happens.
                
                    if ( isNaN ( height ) )
                    {
                        height = width / (4/3);
                    }
                
                    video.setAttribute ( 'width' , width );
                    video.setAttribute ( 'height' , height );
                    streaming = field.name;
                    jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name + ' p a.take_picture' ).show();
                }
            }, false );
        
        navigator.mediaDevices.getUserMedia ( { video: true , audio: false } )
            .then ( function(stream)
            {
                cameraStream = stream;
                video.srcObject = stream;
                video.play();
            } )
            .catch ( function ( err )
            {
                console.log ( "An error occurred" );
                console.log ( err );
            });
        
    } );
}

function clearPicture ( field )
{
    jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name + ' p img' ).remove();
    jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name + ' p a.clear_picture' ).hide();
    jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name + ' p a.activate_camera' ).show();
    jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name + ' p input[type="file"]' ).val ( '' );
}

function takePicture ( field )
{
    if ( width && height )
    {
        jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name + ' p a.activate_camera' ).before ( '<canvas id="canvas" style="display: none"></canvas>' );
        var canvas = jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name + ' canvas#canvas' ) [0];
        var context = canvas.getContext('2d');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        context.drawImage ( video , 0 , 0 , video.videoWidth , video.videoHeight );
        
        var data = canvas.toDataURL ( 'image/png' );
        cameraStream.getTracks().forEach ( function ( track )
        {
            track.stop();
        } );
        cameraStream = undefined;
        jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name + ' video#video' ).remove();
        streaming = false;
        jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name + ' canvas#canvas' ).remove();
        jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name + ' p a.activate_camera' ).before ( '<img width="320" />' );
        jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name + ' p img' ).prop ( 'src' , data );
        let container = new DataTransfer();
        let blob = dataURItoBlob ( data );
        let file = new File ( [ blob] , field.name + '.png' , { type: 'image/png' , lastModified:new Date().getTime() } );
        container.items.add ( file );
        jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name + ' p input[type="file"]' )[0].files = container.files;
        jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name + ' p a.take_picture' ).hide();
        jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name + ' p a.clear_picture' ).show();
    }
    else
    {
        clearPicture ( field );
    }
}

async function showInputFile ( field )
{
    if ( streaming )
    {
        if ( typeof cameraStream != 'undefined' )
        {
            cameraStream.getTracks().forEach ( function ( track )
            {
                track.stop();
            } );
            cameraStream = undefined;
        }
        jQuery ( 'div#initiated div#content section.new-claim div#div_' + field.name  + ' video#video' ).remove();
        jQuery ( 'div#initiated div#content section.new-claim div#div_' + field.name  + ' canvas#canvas' ).remove();
        jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name  + ' p a.take_picture' ).hide();
        streaming = false;
    }
    jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name + ' p a.activate_camera' ).before ( '<img width="320" />' );
    var file = await readFile ( jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name + ' p input[type="file"]' )[0].files[0] );
    jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name + ' p img' ).prop ( 'src' , file );
    jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name  + ' p a.activate_camera' ).hide();
    jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name + ' p a.take_picture' ).hide();
    jQuery ( 'div#initiated div#content section.new-claim form div#div_' + field.name + ' p a.clear_picture' ).show();

}
