import domador from 'domador';
import woofmark from 'woofmark';
import megamark from 'megamark';
import Tagify from '@yaireo/tagify';

window.onload = () => {
  let input = document.querySelector('.tag_input');
  if (!input) {
    return;
  }
  let tags = new Tagify(input);

  let woof = woofmark(document.getElementById("editor"), {
    parseMarkdown: megamark,
    parseHTML: domador,
    html: false,
    markdown: false,
    defaultMode: 'wysiwyg',
  });

  let id = document.getElementById("design_id").value;
  let form = document.getElementById("design_form");

  if (form) {
    form.onsubmit = () => {
      event.preventDefault();
      // gather up all the information
      let info = {
        "title": document.getElementById("title_txt").value,
        "contents": woof.value(),
        "tags": tags.value.map((x) => x.value),
        "category": document.getElementById("category_sel").value,
      };
      fetch(`/edit/design/${id}/`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(info),
      }).then(response => response.json())
        .then(body => window.location.href = `/edit/design/${id}`)
        .catch(err => console.log(err));
      return false;
    };
  }

  fetch(`/api/design/${id}/`)
    .then(res => res.json())
    .then(res => {
      woof.value(res.description);
    });
};
