{% extends "admin/base.html.jinja" %}

{% block header %}
  Create {{ model_name | replace('_', ' ') | title }}
{% endblock %}

{% block content %}
<div id="editor_holder"></div>
<div class="pt-6 flex gap-4">
  <form method="post" id="submit_form">
    <button type="submit" id="submit_button"
            class="px-5 py-2 bg-green-600 text-white text-sm font-medium rounded hover:not-disabled:bg-green-700">
      Create
    </button>

    <input type="hidden" name="editor_data" id="editor_data" value="">
  </form>
  <a href="{{ url_prefix }}/models/{{ model_name }}"
      class="px-5 py-2 bg-gray-200 text-gray-800 text-sm font-medium rounded hover:bg-gray-300">
    Cancel
  </a>
</div>
<script>
    var schema = JSON.parse('{{schema | safe}}')
    const submit_form = document.getElementById("submit_form")
    const submit_button = document.getElementById("submit_button")
    const editor_data = document.getElementById("editor_data")
    document.addEventListener("DOMContentLoaded", function() {
      var editor = new JSONEditor(document.getElementById('editor_holder'),{
        required_by_default: false,
        enable_array_copy: true,
        collapsed: true,
        disable_properties: false,
        object_layout: "table",

        // The schema for the editor
        schema: schema,
      });


      editor.on('change',function() {
        if(!editor.validate().length){
          editor_data.value = JSON.stringify(editor.getValue())
          submit_button.removeAttribute("disabled")
        } else {
          submit_button.setAttribute("disabled", "disabled")
        }
      });

      submit_form.addEventListener("submit", async function(ev){
        if(editor.validate().length){
          ev.preventDefault()
        }
      })
    })
</script>
{% endblock %}
