{% extends "layout.html" %}
{% block content %}
<div class="ic_contentarea">
    <div class="ic_camera">
        <div class="ic_video_overlay"></div>
        <div id="ic_video_div">
            <video id="ic_video">Video stream not available.</video>
        </div>
        <div id='ic_button_div'>
	    	<button class="btn btn-primary" id="frontbutton">Card Front</button>
		    <button class="btn btn-primary" id="backbutton" style='display:none' disabled >Card Back</button>
		</div>
        <button class="btn btn-secondary" id="ic_ready_button" style='display:none' disabled>I confirm my cards are legible</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 class="ic_output_back">
	        <img id="ic_photo_back" alt="Back of card"> 
	    </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 width = 320; // We will scale the photo width to this
var height = 0; // This will be computed based on the input stream

var streaming = false;

function sendpictures() {

	var sendcanvas = document.getElementById('sendcanvas');

	sendcanvas.width = ic_photo_front.width;
	sendcanvas.height = ic_photo_front.height*2;

	var sendcontext = sendcanvas.getContext('2d');
	sendcontext.drawImage(ic_photo_front, 0, 0, ic_photo_front.width, ic_photo_front.height);
	sendcontext.drawImage(ic_photo_back, 0, ic_photo_front.height, ic_photo_front.width, ic_photo_front.height);

	// for testing
	// var combined = new Image;
	// combined.src = sendcanvas.toDataURL('image/png');

	// document.body.appendChild(combined);

    //$.redirect("{{ url_for('self_registration.ic_hook', jotform_id='tester') }}", {'imageBase64': ic_canvas.toDataURL('image/png'), 'csrf_token':'{{ csrf_token() }}'); // this also works

	$.ajax({
	  type: "POST",
	  url: "{{ url_for('self_registration.ic_hook', jotform_id=jotform_id) }}", //"{{ url_for('self_registration.ic_hook', jotform_id='tester') }}",
	  data:{
	    imageBase64: sendcanvas.toDataURL('image/png')
	  },
      success: function(result){
             console.log(result.output);
             window.location.replace("{{ url_for('self_registration.ic_scan_confirmation') }}");//redirect
        }
	})
}

function takepicture(img_element) {
    var context = ic_canvas.getContext('2d');
    if (width && height) {
        ic_canvas.width = width;
        ic_canvas.height = height;
        context.drawImage(ic_video, 0, 0, width, height);

        var data = ic_canvas.toDataURL('image/png');
        img_element.setAttribute('src', data);
    } else {
        clearphoto(img_element);
    }
}

function clearphoto(img_element) {
    var context = ic_canvas.getContext('2d');
    context.fillStyle = "#FFF";
    context.fillRect(0, 0, ic_canvas.width, ic_canvas.height);

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

    img_element.setAttribute('src', data);
    
}

function startup() {

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

    ic_photo_back = document.getElementById('ic_photo_back');
    ic_photo_front = document.getElementById('ic_photo_front');

    frontbutton = document.getElementById('frontbutton');
    backbutton = document.getElementById('backbutton');
    readybutton = document.getElementById('ic_ready_button');
    submitbutton = document.getElementById('ic_submit_button');

    // access video stream from webcam
    navigator.mediaDevices.getUserMedia({
            video: true,
            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);
        
        backbutton.disabled = false; // make back of card button visible and rename self
        backbutton.style='display:inline-block';
        frontbutton.innerHTML = 'Retry Card Front';

        ev.preventDefault();
    }, false);

    backbutton.addEventListener('click', function(ev) {
        takepicture(ic_photo_back);

        readybutton.disabled = false; // make confirm button visible and rename self
        readybutton.style='display:inline-block';
        backbutton.innerHTML = 'Retry Card Back';

        ev.preventDefault();
    }, false);

    readybutton.addEventListener('click', function(ev) {
        submitbutton.disabled = false;
        submitbutton.style='display:inline-block';
        ev.preventDefault();
    }, false);

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

    clearphoto(ic_photo_back);
    clearphoto(ic_photo_front);
}

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

</script>

{% endblock content %}