<style>
  th {
    text-align: left;
  }
  td {
    text-align: right;
  }
</style>
<h1>Spaced Repetition Flashcards</h1>
<h2>Fieldset</h2>
<table>
<tr><th>ID</th><td>{{fieldset.id}}</td></tr>
<tr><th>GUID</th><td>{{fieldset.guid}}</td></tr>
<tr><th>Template set</th><td>{{form-select 'templateset'
templatesets fieldset.templateset}}</td></tr>
<tr><th>Ord</th><td><input type="text" id="ord" value="{{fieldset.ord}}"/></td></tr>
</table>

<h2>Fields</h2>
<button onclick="attach()">Attach</button>
<table id="table-fields">
{{#each fieldset.fields}}
<tr><th>{{@key}}</th><td><input type="text" id="{{@key}}" value="{{this}}"/></td></tr>
{{/each}}
</table>
<button onclick="save()">Save</button>
<button onclick="cancel()">Cancel</button>
<input type="file" id="input" style="display:none;">
<script>
  // Multiple files might be attached
  const fileAttachments = [];
  // On focusout from an input, save element and cursor position in lastInput.
  const lastInput = {};
  document.getElementById('table-fields')
  .addEventListener('focusout',  (e) => {
    lastInput.element = e.target;
    lastInput.selStart = e.target.selectionStart;
    lastInput.selEnd = e.target.selectionEnd;
    const tr = e.target.closest('tr');
    lastInput.label = tr.getElementsByTagName('th')[0].innerHTML;
  });

  // When the template set is changed, update the set of field inputs
  document.getElementById('field-templateset')
  .addEventListener('change', e => {
    document
    .getElementById('table-fields')
    .innerHTML = '';
    fetch('/rest/templateset/' + e.target.value)
    .then(response => {
      if (!response.ok) {
        throw new Error('get templateset failed ' + response.statusText);
      }
      return response.json();
    })
    .then(data => {
      data.fields.forEach(field => {
        const row = document.getElementById('table-fields').insertRow();
        row.innerHTML = '<th>' + field + '</th><td><input type="text" id="'
        + field + '"/></td>';
      });
    })
    .catch(err => {
      alert('get templateset failed with ' + err);
    });
  });

  // When the Save button is clicked
  function save() {
    const data = {
      templateset: document.getElementById('field-templateset').value,
      ord: document.getElementById('ord').value,
      fields: {},
      files: fileAttachments
    };
    document.querySelectorAll('#table-fields input')
    .forEach((input) => {
      data.fields[input.id] = input.value;
    });
    console.log('save data ', data);
    fetch('/fieldset/{{fieldset.id}}', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    })
    .then( response => {
      if (!response.ok) {
        throw new Error(response.url + ': ' + response.status + ': ' +
          response.statusText);
      }
      console.log('response ', response);
      window.close();
    })
    .catch( err => {
      alert('failed');
      console.log('err ', err);
    });
  }

  // When the Cancel button is clicked
  function cancel() {
    window.close();
  }

  // When the Attach button is clicked
  function attach () {
    if (lastInput.element) {
      document.getElementById('input').click();
    }
  }

  document.getElementById('input')
  .onchange = () => {
    const selectedFiles = document.getElementById('input').files;
    console.log('selectedFiles: ', selectedFiles);
    const file = selectedFiles[0];
    console.log('file: ', file);

    new Promise((resolve, reject) => {
      const reader = new FileReader();

      reader.onload = (e) => {
        resolve(e.target.result);
      };

      reader.onerror = (e) => {
        reject(new Error(e));
      };

      reader.readAsDataURL(file);
    })
    .then(data => {
      file_rfc2397 = data;
      fileAttachments.push({
        meta: {
          lastModified: file.lastModified,
          name: file.name,
          size: file.size,
          type: file.type
        },
        data: data
      });
      console.log('fileAttachments: ', fileAttachments);
      const filename = file.name;

      let ref = '';
      if (file.type === 'image/jpeg') {
        // todo: what if the filename includes a ']' character?
        ref = '<img src="' + file.name + '"/>';
      } else if (file.type === 'audio/mpeg') {
        ref = '[sound:' + file.name + ']';
      } else {
        alert('unsupported file type: ' + file.type);
      }
      if (ref) {
        lastInput.element.value =
          lastInput.element.value.substring(0, lastInput.selStart) +
          ref +
          lastInput.element.value.substring(lastInput.selEnd);
      }
    })
    .catch(err => {
      alert('file attachment failed with ' + err);
    });
  };

</script>
