{% extends "base.html" %}
{% block title %}Create Revision - Markdown Editor & Responses{% endblock %}
{% block content %}
    <h3 class="header-space">Create a New Revision</h3>
    <form id="createRevisionForm"
          method="POST"
          action="{{ url_for('index.save_revision') }}">
        <div class="mb-3">
            <label for="revisionDescription" class="form-label">Revision Description</label>
            <textarea class="form-control"
                      id="revisionDescription"
                      name="revision_description"
                      rows="3"
                      required></textarea>
        </div>
        <button type="submit" class="btn btn-primary">Create Revision</button>
    </form>
{% endblock %}
{% block scripts %}
    <script>
    document.addEventListener('DOMContentLoaded', function () {
        const form = document.getElementById('createRevisionForm');
        form.addEventListener('submit', function (event) {
            event.preventDefault(); // Prevent the default form submission
            old_guid = null;
            var new_guid = generateGUID();
            if (getCookie('selected_revision') !== null) {
                var old_guid = getCookie('selected_revision');
            }

            const formData = new FormData(form);
            const url = "{{ url_for('index.save_revision') }}?new_guid=" + new_guid + "&old_guid=" + old_guid;

            fetch(url, {
                method: 'POST',
                body: formData
            })
                .then(response => {
                    if (response.ok) {
                        const revisionName = new_guid;
                        document.cookie = "selected_revision=" + revisionName + "; path=/";
                        window.location.href = "{{ url_for('index.home') }}";
                    } else {
                        alert('Failed to create revision');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('An error occurred');
                });
        });
    });


    function generateGUID() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }
    </script>
{% endblock %}
