{% extends 'scanner/base.html' %}
{% load i18n home_tags scanner_tags %}

{% block styles %}
    {{ block.super }}
    <link href="/static/scanner/css/images.css" rel="stylesheet">
{% endblock %}
{% block sidebar_list %}
    <a href="/"  class="w3-bar-item w3-btn w3-hover-opacity"><i class="fa-solid fa-house w3-text-orange w3-xlarge"></i> {% trans "Retour accueil" %}</a>
    <form method="post" class="w3-bar-item" action="">
        {% csrf_token %}
	    <select id="_sid" name="_sid" class="w3-select w3-margin-bottom" onchange="this.form.submit()" title="{% trans "Ensemble d'expériences" %}">
	        <option value="0">---- {% trans "Session" %}</option>
	        {% for s in sessions %}
	        <option value="{{ s.id }}" {% if s.id == current_session.id %}selected{% endif %}>{{ s }}</option>
	        {% endfor %}
	    </select>
	    <div class="w3-margin-left w3-margin-bottom">
            {% include "scanner/experiment-inc.html" %} 
	    </div>
	    {% if current_session.id and current_experiment %}
            {% multiwell_cards current_session.id current_experiment %}
        {% endif %}
    </form>
    {% if current_session.id %}
    <a href="#" class="w3-bar-item w3-btn w3-hover-opacity" onclick="download_all_images({{ current_session.id }})">
        <i class="fa-solid fa-file-export w3-text-red w3-xlarge"></i> {% trans "Exporter l'ensemble des images de la session" %}<br>
        <span class="w3-margin-left">{{ export_destination }}
    </a>     
    {% endif %}
{% endblock %}

{% block content %}
{% if current_session and current_experiment %}
    <div id="image-grid">
    {% if images %}
        {% for img in images %}
        <div class="w3-card-4 w3-border">
            <div class="w3-padding-small w3-dark-xlight w3-tiny">
                <span>{{ img.uuid }}</span>
                <span class="w3-right">{{ img.index }}</span>
            </div>
            <img class="w3-image" src="{{ img.content }}" onclick="image_preview(this, '{{ img.uuid }}', '{{ img.index }}', '{{ img.ts }}')">
            <div class="w3-container w3-dark-xlight w3-tiny">
                <button class="w3-button w3-round w3-warning w3-padding-1"
                        onclick="image_save('{{ img.uuid }}.jpg', '{{ img.content }}')" title="{% trans 'Télécharger' %}">&nbsp;&#x2B07&nbsp;
                </button>
                <span class="w3-right">{{ img.ts }}</span>
            </div>
        </div>
        {% endfor %}
    {% endif %}
    </div>
{% else %}
<div class="w3-container w3-padding-64" style="max-width:760px; margin:auto;">
    <h3 class="w3-panel w3-blue w3-round-xlarge w3-padding-64 w3-center"> {% trans "Choisir une session" %}</h3>
</div>
{% endif %}
{% endblock %}
{% block modal %}
    {% include "scanner/image-preview.html" %}
{% endblock  %}
{% block js_footer %}
    {{ block.super }}
    <script>
        const container= sId("image-grid");
        const columns  = "{{ conf.default_grid_columns }}";
        const duration = parseInt("{{ duration }}");
        const uuid_btn = sId("btn-" + "{{ uuid }}");
        const image_endpoint = "{% url 'scanner:export_api' %}";
        const export_msg = "{% trans "Confirmer l'export des images." %}";
        const export_msg_long = "{% trans "ATTENTION le processus peut être long!" %}";

        function setGridColumns(col)    { container.style.setProperty("--grid-columns", col); updateActiveButton(col);  }
        function handleMultiwell(b)     { b.classList.add('w3-green'); }
        function image_preview(img, uuid, index, ts)     {
            imagemodal.style.display='block';
            sId('imagepreview').src = img.src;
            sId('imagepreview-uuid').textContent = uuid;
            sId('imagepreview-index').textContent = index;
            sId('imagepreview-ts').textContent = ts;
        }

        function image_save(name, img)  {
            const ok = confirm(export_msg);
            if (!ok) return false;
		    fetch(img)
			    .then(res => res.blob())
			    .then(blob => {
			      const url = URL.createObjectURL(blob);
			      const a = document.createElement('a');
			      a.href = url;
			      a.download = name;
			      document.body.appendChild(a);
			      a.click();
			      document.body.removeChild(a);
			      URL.revokeObjectURL(url);
		    });
        }
        
        function download_all_images(sid) {
            const ok = confirm(export_msg +' '+ export_msg_long);
            if (!ok) return false;
 	        fetch(image_endpoint, {
	            method: 'POST',
	            headers: { 'Content-Type': 'application/json' },
	            body: JSON.stringify({
	                action: 'export_images',
	                sid: sid,
	            })
	        })
	        .then(response => response.json())
	        .then(res => {
	            alert(res.msg);
	        })
	        .catch(error => {
	            console.error('Erreur:', error);
	        });   
	            
        }
	    setGridColumns(columns);
	    if (uuid_btn)
	       handleMultiwell(uuid_btn);
    </script>
{% endblock %}


