/*
 * Copyright (C) 2018 Champs Libres Cooperative <info@champs-libres.coop>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import mime from "mime";

export const download_report = (url, container) => {
  var download_text = container.dataset.downloadText,
    alias = container.dataset.alias;

  window
    .fetch(url, { credentials: "same-origin" })
    .then((response) => {
      if (!response.ok) {
        throw Error(response.statusText);
      }

      return response.blob();
    })
    .then((blob) => {
      var content = URL.createObjectURL(blob),
        link = document.createElement("a"),
        type = blob.type,
        hasForcedType = "mimeType" in container.dataset,
        extension;

      if (hasForcedType) {
        // force a type
        type = container.dataset.mimeType;
        blob = new Blob([blob], { type: type });
        content = URL.createObjectURL(blob);
      }

      const extensions = new Map();
      extensions.set(
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "xlsx",
      );
      extensions.set("application/vnd.oasis.opendocument.spreadsheet", "ods");
      extensions.set("application/vnd.ms-excel", "xlsx");
      extensions.set("text/csv", "csv");
      extensions.set("text/csv; charset=utf-8", "csv");

      extension = extensions.get(type);

      link.appendChild(document.createTextNode(download_text));
      link.classList.add("btn", "btn-action");
      link.href = content;
      link.download = alias;
      if (extension !== false) {
        link.download = link.download + "." + extension;
      }
      container.innerHTML = "";
      container.appendChild(link);
    })
    .catch(function (error) {
      console.error(error);
      var problem_text = document.createTextNode("Problem during download");

      container.replaceChild(problem_text, container.firstChild);
    });
};
