export default {
  name: "export",

  getReducer: () => {
    const initialData = {
      loadingCsv: false,
      loadingGeoJSON: false,
    };

    return (state = initialData, { type, payload }) => {
      switch (type) {
        case "EXPORT_TO_CSV_INITIATED":
        case "EXPORT_TO_CSV_FINISHED":
        case "EXPORT_TO_GEOJSON_INITIATED":
        case "EXPORT_TO_GEOJSON_FINISHED":
          return Object.assign({}, state, payload);
        default:
          return state;
      }
    };
  },
  doExportToCSV: (data) => ({ dispatch, store }) => {
    //Modify FeatureCollection to an array, to generate csv.
    const features = data.features;
    let csvArray = [];
    const columnHeaders = Object.keys(features[0].properties);
    csvArray.push(columnHeaders);

    features.forEach((item, i) => {
      const values = Object.keys(item.properties).map((value) => {
        return item.properties[value];
      });
      csvArray.push(values);
    });

    store.doGenerateCsv(csvArray);
  },
  doGenerateCsv: (csvArray) => ({ dispatch, store }) => {
    dispatch({
      type: "EXPORT_TO_CSV_INITIATED",
      payload: {
        loadingCsv: true,
      },
    });
    const processRow = (row) => {
      let finalVal = "";
      for (let j = 0; j < row.length; j++) {
        let innerValue = row[j] === null ? "" : row[j].toString();
        if (row[j] instanceof Date) {
          innerValue = row[j].toLocaleString();
        }
        let result = innerValue.replace(/"/g, '""');
        if (result.search(/("|,|\n)/g) >= 0) result = '"' + result + '"';
        if (j > 0) finalVal += ",";
        finalVal += result;
      }
      return finalVal + "\n";
    };

    let csvFile = "";
    for (let i = 0; i < csvArray.length; i++) {
      csvFile += processRow(csvArray[i]);
    }

    let blob = new Blob([csvFile], { type: "text/csv;charset=utf-8;" });
    if (navigator.msSaveBlob) {
      // IE 10+
      navigator.msSaveBlob(blob, "export.csv");
    } else {
      let link = document.createElement("a");
      if (link.download !== undefined) {
        // feature detection
        // Browsers that support HTML5 download attribute
        let url = URL.createObjectURL(blob);
        link.setAttribute("href", url);
        link.setAttribute("download", "export.csv");
        link.style.visibility = "hidden";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    }

    dispatch({
      type: "EXPORT_TO_CSV_FINISHED",
      payload: {
        loadingCsv: false,
      },
    });
  },
  doGenerateGeoJSON: (geojson) => ({ dispatch, store }) => {
    dispatch({
      type: "EXPORT_TO_GEOJSON_INITIATED",
      payload: {
        loadingGeoJSON: true,
      },
    });
   
    let blob = new Blob([JSON.stringify(geojson)], { type: "text/csv;charset=utf-8;" });
    if (navigator.msSaveBlob) {
      // IE 10+
      navigator.msSaveBlob(blob, "export.geojson");
    } else {
      let link = document.createElement("a");
      if (link.download !== undefined) {
        // feature detection
        // Browsers that support HTML5 download attribute
        let url = URL.createObjectURL(blob);
        link.setAttribute("href", url);
        link.setAttribute("download", "export.geojson");
        link.style.visibility = "hidden";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    }

    dispatch({
      type: "EXPORT_TO_GEOJSON_FINISHED",
      payload: {
        loadingGeoJSON: false,
      },
    });
  },
};
