/** Download/upload JSON bundles for profile, preset, and sequence import/export. */

window.downloadJsonFile = function downloadJsonFile(filename, data) {
  const text = typeof data === 'string' ? data : JSON.stringify(data, null, 2);
  const blob = new Blob([text], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename || 'bundle.json';
  document.body.appendChild(a);
  a.click();
  a.remove();
  URL.revokeObjectURL(url);
};

window.pickJsonFile = function pickJsonFile() {
  return new Promise((resolve) => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'application/json,.json';
    input.style.display = 'none';
    document.body.appendChild(input);
    input.addEventListener('change', () => {
      const file = input.files && input.files[0];
      input.remove();
      if (!file) {
        resolve(null);
        return;
      }
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result);
      reader.onerror = () => resolve(null);
      reader.readAsText(file);
    });
    input.click();
  });
};

window.parseJsonFileText = function parseJsonFileText(text) {
  if (text == null || text === '') {
    return null;
  }
  try {
    return JSON.parse(text);
  } catch (e) {
    return null;
  }
};
