{% extends "base.html" %}

{% block styles %}
    {{ super() }}
    <link rel="StyleSheet" href="/edit.css" type="text/css" media="screen" />
{% endblock styles %}

{% block content %}

{% if subaction and subaction == "preview" %}
<div id="preview">{{ content | markdown | safe }}</div>
{% endif %}

<form method="post">
  <button id="resolve-button" name="subaction" value="resolvelinks">Resolve Wikilinks</button>
  <textarea id="edit-area" name="content">{{ content }}</textarea>
  <label id="edit-author-remember-label">Remember author name: <input type="checkbox" id="edit-author-remember" name="author-remember" /></label>
  <label id="edit-author-label">Author name: <input type="text" id="edit-author" name="author" value="{{ author | default(value="") }}" /></label>
  <label id="edit-summary-label">Edit summary: <input type="text" id="edit-summary" name="summary" value="{{ summary | default(value="") }}" /></label>
  <div id="edit-buttons">
    <button name="subaction" value="preview">Preview</button>
    <button name="subaction" value="submit">Submit</button>
  </div>
</form>

<script type="text/javascript">
// save author name if enabled
const authorName = document.getElementById("edit-author");
const rememberAuthor = document.getElementById("edit-author-remember");
function saveAuthorName () {
    document.cookie = `author=${encodeURIComponent(rememberAuthor.checked ? authorName.value : '')}; path=/`
}

rememberAuthor.addEventListener("change", saveAuthorName);
authorName.addEventListener("change", saveAuthorName);

// load author name
const authorCookieValue = document.cookie
  .split("; ")
  .find((row) => row.startsWith("author="))
  ?.split("=")[1];

if (authorCookieValue) {
    rememberAuthor.checked = true;
    authorName.value = decodeURIComponent(authorCookieValue);
}

const editArea = document.getElementById("edit-area");
document.getElementById("resolve-button").addEventListener("click", event => {
    let formData = new FormData();
    formData.append("content", editArea.value);
    formData.append("summary", "");
    formData.append("subaction", "");
    formData.append("author", "");
    fetch("?action=resolvelinks", {
        method: 'POST',
        body: formData
    }).then(result => result.text())
      .then(body => editArea.value = body);

    event.preventDefault();
});
</script>
{% endblock content %}
