{% extends 'base.html' %}
{% load static %}

{% block body %}
    <link href="{% static 'css/grabacion.css' %}" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://stephino.github.io/dist/recorder.js"></script>


    <script src="//cdn.jsdelivr.net/jquery/2.1.4/jquery.js"></script>
    <script src="//wzrd.in/standalone/blob-util@latest"></script>

    <input type="text" id="formname" value="{{ formulario.titulo }}" hidden>
    <div class="card mb-5" style="width: 80% !important;">
        <div class="card-body">
            <h1 class="card-title mb-4">
                Personal Information
            </h1>

            {% for info in informaciones %}
                <fieldset class="form-group">
                    <label class="bmd-label-floating" for="inputDato{{ forloop.counter0 }}">*{{ info.pregunta }}</label>
                    {% if info.tipo != 'sino' %}
                        <input class="form-control" type="text" name="{{ info.id }}" id="inputDato{{ forloop.counter0 }}" autofocus>
                        <input name="{{ info.tipo }}" id="infoType{{ forloop.counter0 }}" hidden>
                    {% else %}
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="{{ info.id }}" id="inputDatoYes{{ forloop.counter0 }}">
                            <label class="form-check-label" for="flexRadioDefault1">
                               Yes
                            </label>

                            <input class="form-check-input ml-3" type="radio" name="{{ info.id }}" id="inputDatoNo{{ forloop.counter0 }}">
                            <label class="form-check-label ml-5" for="flexRadioDefault1">
                               No
                            </label>
                            <input name="{{ info.tipo }}" id="infoType{{ forloop.counter0 }}" hidden>
                        </div>
                    {% endif %}

                </fieldset>
            {% endfor %}
        </div>
    </div>

    {% for seccion in secciones %}
        <div class="card mb-5" name="{{ seccion.id }}" id="card{{ forloop.counter0 }}" style="width: 80% !important;">
        {% if seccion.texto %}
            <h5 class="card-header" style="white-space: pre-wrap">{{ seccion.texto }}</h5>
        {% endif %}
        <div class="card-body">
            <div class="row-fluid justify-content-center align-content-center" id="audioControls">
                {% if seccion.imagen %}
                    <img class="mb-5" src="{% static seccion.imagen %}" style="max-height:400px">
                    <br>
                {% endif %}

                {% if seccion.audio %}
                    <audio controls controlsList="nodownload" src="{% static seccion.audio %}">
                    </audio>
                {% endif %}

                <div class="holder mt-4" id="holderAudio{{ forloop.counter0 }}">
                    <h5 class="text-dark">Audio Respuesta</h5>
                    <div data-role="controls{{ forloop.counter0 }}" class="controls" id="cont{{ forloop.counter0 }}">
                        <button type="button" class="btn border rounded" onclick="grab({{ forloop.counter0 }})" id="btn{{ forloop.counter0 }}"><i class="fa fa-microphone pr-2" aria-hidden="true"></i>Record</button>
                    </div>
                    <div data-role="recordings{{ forloop.counter0 }}" class="recordings" id="rec{{ forloop.counter0 }}"></div>
                </div>

            </div>
        </div>
    </div>
    {% endfor %}

    <div class="col mb-5"></div>


{% endblock %}

{% block footer1 %}
{% endblock %}

{% block action_buttons %}

{% endblock %}

{% block javascripts %}
    <script>
        var cont = 0
        var cont_recorder = 0
        var last_id = null
        var blob_list = new Array(20).fill(null);

        var myRecorder = {
            objects: {
                context: null,
                stream: null,
                recorder: null
            },
            init: function () {
                if (null === myRecorder.objects.context) {
                    myRecorder.objects.context = new (
                            window.AudioContext || window.webkitAudioContext
                            );
                }
            },
            start: function () {
                var options = {audio: true, video: false};
                navigator.mediaDevices.getUserMedia(options).then(function (stream) {
                    myRecorder.objects.stream = stream;
                    myRecorder.objects.recorder = new Recorder(
                            myRecorder.objects.context.createMediaStreamSource(stream),
                            {numChannels: 1}
                    );
                    myRecorder.objects.recorder.record();
                }).catch(function (err) {});

            },
            stop: function (listObject, id_num) {

                if (null !== myRecorder.objects.stream) {
                    myRecorder.objects.stream.getAudioTracks()[0].stop();
                }
                if (null !== myRecorder.objects.recorder) {
                    myRecorder.objects.recorder.stop();

                    // Validate object
                    if (null !== listObject
                            && 'object' === typeof listObject
                            && listObject.length > 0) {
                        // Export the WAV file
                        myRecorder.objects.recorder.exportWAV(function (blob) {
                            var today = new Date();
                            var filename = String(String(today.getMinutes()) + String(today.getSeconds() + String(today.getMilliseconds())))
                            console.log(filename)

                            if (filename.length<6){
                                while(filename.length<6){
                                    filename = filename + "0"
                                }
                            }else if(filename.length>6){
                                filename = filename.substring(0,6)
                            }

                            console.log(filename)
                            blob_list[id_num] = blob;
                            //createDownloadLink(blob_copy, filename)

                            var url = (window.URL || window.webkitURL)
                                .createObjectURL(blob);

                            // Prepare the playback
                            var audioObject = $('<audio controls></audio>')
                                .attr('controlsList', "nodownload")
                                .attr('src', url);

                            // Prepare the download link
                            var downloadObject = $('<a hidden>&#9660;</a>')
                                .attr('href', url)
                                .attr('id', 'a'+id_num)
                                .attr('name', filename)
                                .attr('download', new Date().toUTCString() + '.wav');

                            // Wrap everything in a row
                            var holderObject = $('<div class="row"></div>')
                                .append(audioObject)
                                .append(downloadObject);
                            cont++;

                            // Append to the list

                            listObject.append(holderObject);


                        });
                    }
                }


            }
        };

        function grab(id_num){
            var $ = jQuery;
            var id = 'btn' + id_num;

            // Prepare the recordings list
            var recordings = "recordings" + id_num;
            var controls = "controls" + id_num;
            var data = '[data-role= ' + recordings +']';
            var listObject = $(data);

            var listChild = document.getElementById("rec"+id_num);
            if(listChild.childElementCount > 0){
                listChild.removeChild(listChild.childNodes[0]);
            }

            if(last_id != id_num){
                cont_recorder = 0;
            }
            // Initialize the recorder
            if(cont_recorder==0){
                myRecorder.init();
                last_id = id_num;
            }

            cont_recorder++;

            // Get the button state
            var buttonState = !!$(this).attr('data-recording');

            // Toggle
            if (!buttonState) {
                $(this).attr('data-recording', 'true');
                myRecorder.start();

                var buton = document.getElementById(id);
                buton.innerText="";
                buton.style.backgroundColor = '#ff2038';


                var icon = document.createElement("i");
                icon.className= "fa fa-stop pr-2";
                icon.setAttribute("aria-hidden", true);
                buton.append(icon, "Stop");

            } else {
                $(this).attr('data-recording', '');
                myRecorder.stop(listObject, id_num);

                var buton = document.getElementById(id);
                buton.innerText="";
                buton.style.backgroundColor = '#745AAA';


                var icon = document.createElement("i");
                icon.className= "fa fa-microphone pr-2";
                icon.setAttribute("aria-hidden", true);
                buton.append(icon, "Record");

            }

        };


        function createDownloadLink(blob_f, filename, seccion) {

            var fd = new FormData();
            console.log(typeof blob_f);
            fd.append('audio',blob_f, filename);
            var framerate = myRecorder.objects.recorder.context.sampleRate;
            $.ajax({
                url: "{% url 'graficcontestar' formulario.titulo 1234 5678 lastusuario %}".replace(/1234/, seccion).replace(/5678/, framerate),
                type: "POST",
                data: fd,
                processData: false,
                contentType: 'application/json',
                success : function(json,data) {
                },
                error : function(xhr, errmsg, err) {
                    alert("Audio could not be saved!");
                    return false;
                }
            });

        }

        function passForm(secciones_lenght){

            var titulform = document.getElementById('formname').value;

            var data_dict = {'formtitulo': titulform,
                            'numSecciones':secciones_lenght,
                            'numDatos': {{numDatos}} }

            for(var i = 0; i<{{ numDatos }}; i++){
                var dato = document.getElementById('inputDato'+i);
                data_dict['dato'+i] = {'respuesta': dato.value, 'informacion': dato.name}
            }

            for(var i = 0; i<secciones_lenght; i++){
                var idseccion = document.getElementById('card'+i).getAttribute('name');
                console.log(idseccion)
                var audio = document.getElementById('a'+i).name;

                data_dict['seccion'+i] =  {'id_seccion': idseccion, 'audio': audio}
            }
            $.ajax({
                url: "{% url 'formcontestar' %}",
                type: "POST",
                data: data_dict,
                success : function(json,data) {
                    location.href = "{% url 'adminprofile' user.username %}"
                },
                error : function(xhr, errmsg, err) {
                    alert("Answer could not be saved!");
                }
            });

        }
    </script>

    <script type="text/javascript">
        function action_submit(secciones_lenght){
            //if(!comprobar_inputs(secciones_lenght)){
                //return false;            }



            for(var i = 0; i<secciones_lenght; i++){
                createDownloadLink(blob_list[i], document.getElementById('a'+i).name, String(i+1));
            }
            passForm(secciones_lenght);
        }

        function comprobar_inputs(secciones_lenght){
            console.log(secciones_lenght);
            if(!correct_data()){
                return false;
            }

            if(!correct_datos()){
                return false;
            }

            if(!correct_audios(secciones_lenght)){
                return false;
            }

            return true;
        }

        function correct_data(){
            var nacimiento = document.getElementById("inputNacimiento").value;
            var day = nacimiento.substring(0,2);
            var month = nacimiento.substring(3,5);
            var year = nacimiento.substring(6,10);

            if (nacimiento.length != 10){
                alert("Fecha de nacimiento incorrecta. El formato debe ser dd/mm/yyyy.");
                return false;
            }

            day = parseInt(day);
            month = parseInt(month);
            year = parseInt(year);

            if (day <= 0 || day >31 || month < 1 || month > 12 ){
                alert("Fecha de nacimiento incorrecta. El formato debe ser dd/mm/yyyy.");
                return false;
            }

            return true;
        }

        function correct_datos(){
            var estudios = document.getElementById("inputEstudios").value;
            var pais = document.getElementById("inputPais").value;
            var ciudad = document.getElementById("inputCiudad").value;
            var paisActual = document.getElementById("inputPaisActual").value;
            var ciudadActual = document.getElementById("inputCiudadActual").value;

            if(!estudios || !pais || !ciudad || !paisActual || !ciudadActual){
                alert("Debes rellenar todas las casillas del formulario.");
                return false;
            }
            return true;

        }

        function correct_audios(secciones_lenght){
            for(var i = 0; i<secciones_lenght; i++){
                var holder = document.getElementById("rec"+i);
                if(!holder.hasChildNodes()){
                    alert("Debes grabar un audio para cada sección.");
                    return false;
                }
            }
            return true;
        }

        function hasWhiteSpace(s) {
          return /\s/g.test(s);
        }

    </script>

{% endblock %}