{% extends 'base.html' %}

{% block title %}Create Environment{% endblock %}

{% block content %}
{% if message %}
<pre class="alert alert-danger" role="alert">{{ message }}</pre>
{% endif %}

<form id="create-environment">
    <div>
        <label for="namespace">Namespace</label>
        <select class="form-select" name="namespace" id="namespace" aria-label="namespace">
            {% for namespace in namespaces %}
            <option {% if loop.index == 0 %}selected{% endif %} value="{{ namespace.name }}">{{ namespace.name }}</option>
            {% endfor %}
        </select>
    </div>

    <div class="custom-file">
        <input type="file" class="custom-file-input" id="customFile">
        <label class="custom-file-label" for="customFile">Choose file</label>
    </div>

    <div class="form-group">
        <label for="specification">Specification:</label>
        <div id="editor" style="height: 400px;">{{ specification or "" }}</div>
        <textarea name="specification" id="specification" style="display: none;"></textarea>
    </div>

    <button type="submit" class="btn btn-primary mb-2">Submit</button>
</form>

<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.js" integrity="sha512-GZ1RIgZaSc8rnco/8CXfRdCpDxRCphenIiZ2ztLy3XQfCbQUSCuk8IudvNHxkRA3oUg6q0qejgN/qqyG1duv5Q==" crossorigin="anonymous"></script>
<script>
 const editor = ace.edit("editor");
 editor.setTheme("ace/theme/github");
 editor.getSession().setMode("ace/mode/yaml");
 editor.setFontSize("20px");

 const textarea = document.querySelector('textarea[name="specification"]');
 editor.getSession().on("change", function() {
     textarea.value = editor.getSession().getValue();
 })

 const fileSelector = document.querySelector('#customFile');
 fileSelector.addEventListener('change', (event) => {
     const reader = new FileReader();
     reader.addEventListener('load', (event) => {
         textarea.value = event.target.result;
         editor.setValue(event.target.result, 1);
     });
     reader.readAsText(event.target.files[0]);
 });

 function bannerMessage(message) {
     let banner = document.querySelector('#message');
     banner.innerHTML = message;
 }

 async function createEnvironmentHandler(event) {
     event.preventDefault();

     let url = "{{ url_for('api_post_specification') }}";
     let namespaceInput = document.querySelector('#namespace');
     let specificationInput = document.querySelector('#specification');

     let response = await fetch(url, {
         method: 'POST',
         headers: {
             'Content-Type': 'application/json'
         },
         body: JSON.stringify({
             'namespace': namespaceInput.value,
             'specification': specificationInput.value,
         })
     });

     if (response.ok) {
         window.location = "{{ url_for('ui_list_environments') }}";
     } else {
         let data = await response.json();
         let message = data.message;
         if (message.search('[\n\r]') !== -1) {
             bannerMessage(`<pre class="alert alert-danger col">${data.message}</pre>`);
         } else {
             bannerMessage(`<div class="alert alert-danger col">${data.message}</div>`);
         }
     }
 }

 let form = document.querySelector('#create-environment');
 form.addEventListener('submit', (event) => createEnvironmentHandler(event));
</script>
{% endblock %}
