import { state } from "./state.js";

/**
 * Retrieves a template from the server and sets it as the value of a specified destination element.
 *
 * @param {string} orig - The ID of the element containing the original template value.
 * @param {string} dest - The ID of the destination element where the retrieved template will be set.
 * @return {Promise} A Promise that resolves when the template is successfully retrieved and set as the value of the destination element.
 */
export function retrieveTemplate(orig, dest) {
    const temp = document.querySelector('#' + orig);
    if (temp.value == '0') {
        document.querySelector('#' + dest).value = '';
        return;
    }
    fetch('/retrieve-template', {
        method: 'POST',
        headers: {
            'Content-Type': 'plain/text'
        },
        body: JSON.stringify({
            'template': temp.value
        })
    })
        .then(response => response.text())
        .then(results => {
            const div = document.querySelector('#' + dest);
            div.value = results;
            state.textDirty = true;
        });
}

/**
 * Saves the template by sending a POST request to the server with template data.
 */
export function saveTemplate() {
    fetch('/save-template', {
        method: 'POST',
        headers: {
            'Content-Type': 'plain/text'
        },
        body: JSON.stringify({
            'template_id': document.querySelector('#template_id').value,
            'template_name': document.querySelector('#template_name').value,
            'template_value': document.querySelector('#template_value').value,
        })
    })
        .then(response => response.text())
        .then(results => {
            alert(results);
        });
}
