$(document).ready(function () {
    //https://medium.com/swlh/how-to-access-webcam-and-take-picture-with-javascript-b9116a983d78
    const webcamElement = document.getElementById('webcam');
    const canvasElement = document.getElementById('canvas');
    const snapSoundElement = document.getElementById('snapSound');
    const webcam = new Webcam(webcamElement, 'user', canvasElement, snapSoundElement);


    $('#live_endocscopy_link').on('click', function(){
        if ($('#live_endocscopy_link').hasClass('active'))
        {
            webcam.start()
              .then(result =>{
                console.log("webcam started");
                $('#take_picture').focus();
              })
              .catch(err => {
                console.log(err);
            });

        }
    });

    $(document).keypress(function(event){
        if ($('#live_endocscopy_link').hasClass('active'))
        {
            take_picture();
        }
    });

    $('#take_picture').on('click', function(){
        take_picture();
    })

    $('.nav-link').on('click', function(){
        if ($(this).attr('id') != 'live_endocscopy_link')
            webcam.stop()
    });

    function makeblob(dataURL) {
        var BASE64_MARKER = ';base64,';
        if (dataURL.indexOf(BASE64_MARKER) == -1) {
            var parts = dataURL.split(',');
            var contentType = parts[0].split(':')[1];
            var raw = decodeURIComponent(parts[1]);
            return new Blob([raw], { type: contentType });
        }
        var parts = dataURL.split(BASE64_MARKER);
        var contentType = parts[0].split(':')[1];
        var raw = window.atob(parts[1]);
        var rawLength = raw.length;

        var uInt8Array = new Uint8Array(rawLength);

        for (var i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
        }

        return new Blob([uInt8Array], { type: contentType });
    }

    function loadWOrec(from, blob){
        $('#start_rec').attr("disabled", true);
        $('#save_picture').attr("disabled", true);
        $('#request_waiting').show();
        $('#progress_text').html('Загрузка снимков');
        var organ = 0
        if($('#btnradio_ear').is(":checked"))
            organ = 1
        if($('#btnradio_throat').is(":checked"))
            organ = 2
        if($('#btnradio_nose').is(":checked"))
            organ = 3

        var fileList = document.getElementById('file_input').files;
        var formData = new FormData();
        var poll = null;
        var i = 0
        if (from == 'source')
            for(i=0;i<fileList.length;i++)
            {
                if (fileList[i].type.includes('image'))
                {
                    formData.append("files", fileList[i]);
                    i += 1;
                }
            }
        if (from == 'webcam')
//            $.each($('.endo_image'), function(e) {
                formData.append("files", makeblob(blob));
                i += 1;
//            });
        if (i > 0)
        {
            $.ajax({
                type:'POST',
                data: formData,
                url: '/upload_images',
                processData: false,  // tell jQuery not to process the data
                contentType: false,  // tell jQuery not to set contentType
                success: (data) => {
//                    $('#photos').empty();
//                    $('#imgs_preview').empty();
//                    $('#file_input').val(null);
                    $('#pre_load').show();
                    $('#file-input-greenspan').html('');
                    $('#start_rec').attr("disabled", false);
                    $('#save_picture').attr("disabled", false);
                    $('#request_waiting').hide();
                    for(fnum in data['files'])
                        $('#photos').append('<div class="col-3 my-2"><button type="button" aria-label="Close" class="btn-close remove-picture" style="background-color: #0d6efd; display: block; position: absolute; margin: 5px;"></button><img class="endo_image" data-type="saved" data-name=' + data['files'][fnum] + ' id="rrr" src="/img/'+data['files'][fnum]+'" style="width: 100%;"></div>')

                },
                error:function (jqXHR, exception) {
                    $('#start_rec').attr("disabled", false);
                    $('#save_picture').attr("disabled", false);
                    $('#request_waiting').hide();
//                    after_error();
                }
            });
        }
        else
        {
            $('#start_rec').attr("disabled", false);
            $('#save_picture').attr("disabled", false);
            $('#request_waiting').hide();
//            after_error();
        }
    }

    function take_picture(){
        let picture = webcam.snap();

//        $('#download-photo').attr('src', picture);
//        $('#download').attr('href', picture);
        if($('#eleps').is(':checked'))
            loadWOrec('webcam', picture);
        else
            $('#photos').append('<div class="col-3 my-2"><button type="button" aria-label="Close" class="btn-close remove-picture" style="background-color: #0d6efd; display: block; position: absolute; margin: 5px;"></button><img class="endo_image" data-type="blob" id="rrr" src="'+picture+'" style="width: 100%;"></div>')
        $('.remove-picture').on('click', function(){
            $(this).parent().remove();
        })
    }





    $('.remove-picture').on('click', function(){
        $(this).parent.remove();
    })



});
