{% extends "layout.html" %}
{% block content %}

<div class="ic_contentarea h-100" id='upload_card_div'>
    <video id="ic_video">Video stream not available.</video>
    <div id='video_overlay'></div>
    <img id="ic_photo_front" alt="Front of card" style='display:none'>
    <div id='video_overlay_buttons'>
        <button class="btn btn-lg btn-bd-signup-inverted" id="take_photo">Scan</button>
        <button class="btn btn-lg btn-bd-signup-inverted" id="try_again" style='display:none' disabled>Rescan</button>
        <button class="btn btn-lg btn-bd-signup-inverted" id="ic_submit_button" style='display:none' disabled>Submit</button>
    </div>
</div>

<canvas id="ic_canvas"></canvas>
<canvas id="sendcanvas"></canvas>
<div class="lds-circle"><div></div></div>

<!-- <div class="ic_contentarea h-100">

    <div id="ic_video_div h-100">
        <video id="ic_video">Video stream not available.</video>
        <div id='ic_button_div'>
            <button class="btn btn-primary" id="take_photo">Take Photo</button>
            <button class="btn btn-success" id="ic_submit_button" style='display:none' disabled>Submit</button>
        </div>

        <canvas id="ic_canvas"></canvas>
        <canvas id="sendcanvas"></canvas>

        <div>
            <div class="ic_output_front">
                <img id="ic_photo_front" alt="Front of card"> 
            </div>
        </div>
    </div>

</div> -->

<!-- https://flask-wtf.readthedocs.io/en/stable/csrf.html -->
<script type="text/javascript">
    var csrf_token = "{{ csrf_token() }}";

    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrf_token);
            }
        }
    });
</script>

<script type="text/javascript">

var streaming = false;

$(document)
  .ajaxStart(function () {
    $('.lds-circle')[0].style.display = "block";
  })
  .ajaxStop(function () {
    $('.lds-circle')[0].style.display = "none";
  });

function sendpictures() {

    //imagemarker.clientHeight)
	
    //$.redirect("{{ url_for('submit_vax.card_hook') }}", {'imageBase64': ic_canvas.toDataURL('image/png'), 'csrf_token':'{{ csrf_token() }}'); // this also works

	$.ajax({
	  type: "POST",
	  url: "{{ url_for('submit_vax.card_hook') }}",
	  data:{
	    imageBase64: sendcanvas.toDataURL('image/png')
	  },
      success: function(result){
             console.log(result.output);
             window.location.replace("{{ url_for('submit_vax.upload_details') }}");//redirect
        }
	})
}

function takepicture() {
    
    imagemarker = document.getElementById('video_overlay');

    var markerRef = imagemarker.getBoundingClientRect();
    var videoRef = ic_video.getBoundingClientRect();

    ic_canvas.width = markerRef.width;
    ic_canvas.height = markerRef.height;

    sendcanvas.width = 600;
    sendcanvas.height = 600 * markerRef.height/markerRef.width;

    var scale = 0;

    if (videoRef.height>=ic_video.videoHeight) {
        // limiting dimension is up down
        scale = videoRef.height/ic_video.videoHeight; // scale of video  (pixels on screen/actual pixels)
    } else {
        scale = videoRef.width/ic_video.videoWidth;
    }

    context.drawImage(
        ic_video,
        (ic_video.videoWidth - markerRef.width/scale) / 2,
        (ic_video.videoHeight - markerRef.height/scale) / 2,
        markerRef.width/scale,
        markerRef.height/scale, // this is how many pixels are packed into the vertical axis inside the box (there are more than the box is tall because its distorted)
        0,
        0,
        markerRef.width,//imagemarker.clientWidth,
        markerRef.height)//imagemarker.clientHeight)

    sendcontext.drawImage(
        ic_video,
        (ic_video.videoWidth - markerRef.width/scale) / 2,
        (ic_video.videoHeight - markerRef.height/scale) / 2,
        markerRef.width/scale,
        markerRef.height/scale, // this is how many pixels are packed into the vertical axis inside the box (there are more than the box is tall because its distorted)
        0,
        0,
        sendcanvas.width,//imagemarker.clientWidth,
        sendcanvas.height)

    var data = ic_canvas.toDataURL('image/png');
    ic_preview.setAttribute('src', data);

    ic_preview.style.display = 'inline-block';

}

function clearphoto() {
    // context.fillStyle = "#FFF";
    // context.fillRect(0, 0, ic_canvas.width, ic_canvas.height);

    // var data = ic_canvas.toDataURL('image/png');

    // ic_preview.setAttribute('src', data);
    
}

function startup() {

    ic_video = document.getElementById('ic_video');
    ic_canvas = document.getElementById('ic_canvas');
    sendcanvas = document.getElementById('sendcanvas');

    ic_preview = document.getElementById('ic_photo_front');

    ic_photo_front = document.getElementById('ic_photo_front');

    frontbutton = document.getElementById('take_photo');
    tryagainbutton = document.getElementById('try_again');
    submitbutton = document.getElementById('ic_submit_button');

    context = ic_canvas.getContext('2d');
    sendcontext = sendcanvas.getContext('2d');

    // access video stream from webcam
    navigator.mediaDevices.getUserMedia({
            video: { facingMode: "environment" },
            audio: false
        })
        // on success, stream it in video tag
        .then(function(stream) {
            ic_video.srcObject = stream;
            ic_video.play();
        })
        .catch(function(err) {
            console.log("An error occurred: " + err);
        });

    ic_video.addEventListener('canplay', function(ev) {
        if (!streaming) {
            // height = ic_video.videoHeight / (ic_video.videoWidth / width);

            // if (isNaN(height)) {
            //     height = width / (4 / 3);
            // }

            // ic_video.setAttribute('width', width);
            // ic_video.setAttribute('height', height);
            // ic_canvas.setAttribute('width', width);
            // ic_canvas.setAttribute('height', height);
            streaming = true;
        }
    }, false);

    frontbutton.addEventListener('click', function(ev) {
        takepicture(ic_photo_front);
        
        frontbutton.disabled = true;
        frontbutton.style.display = 'none';

        tryagainbutton.disabled = false; // make back of card button visible and rename self
        tryagainbutton.style.display = 'inline-block';

        submitbutton.disabled = false; 
        submitbutton.style.display = 'inline-block';
        //frontbutton.innerHTML = 'Retry Card Front';

        ev.preventDefault();
    }, false);

    tryagainbutton.addEventListener('click', function(ev) {

        ic_preview.style = 'display:none';

        tryagainbutton.disabled = true;
        tryagainbutton.style.display = 'none';

        frontbutton.disabled = false; // make back of card button visible and rename self
        frontbutton.style.display = 'inline-block';

        submitbutton.disabled = true;
        submitbutton.style.display = 'none';

    ev.preventDefault();
    }, false);

    submitbutton.addEventListener('click', function(ev) {
        sendpictures();
        ev.preventDefault();
    }, false);

    clearphoto(ic_photo_front);
}

window.onload = function () { 
	startup();
}

</script>

{% endblock content %}