;
/*************************************************************
 *
 * Copyright (c) 2024 ysrock Co., Ltd.	<info@ysrock.co.jp>
 * Copyright (c) 2024 Yasuo Sugano	<sugano@ysrock.co.jp>
 *
 * Version	: 1.0.0
 * Update	  : 2024.01.17
 *
 ************************************************************/
'use strict';
(function(){
  

  /**
   * JSON形式をCSVに変換
   *
   *  JSONデータをCSVデータに変換
   *    window['json2csv']( $json );
   *      @param  json $json
   *      @return string
   *
   *  JSONデータからCSVデータをダウンロードする
   *    window['json2csv']( JSON, $filename );
   *      @param  json $json
   *      @param  string $filename
   */
  let json2csv = {
    construct: (json, name) => {
      let csv = json2csv.csv(json);
      if (name === undefined) return csv;
      json2csv.download(csv, name);
    },
    help: () => {
      let text = "";
      text += " * Copyright (c) 2024 ysrock Co., Ltd.	<info@ysrock.co.jp>\n";
      text += " * Copyright (c) 2024 Yasuo Sugano	<sugano@ysrock.co.jp>\n";
      text += " *\n";
      text += " * Version	: 1.0.0\n";
      text += " * Update	: 2024.01.17\n";
      text += " *\n";
      text += " *\n";
      text += " *    JSONデータをCSVデータに変換\n";
      text += " *      window['json2csv']( " + '$' + "json );\n";
      text += " *        @param  json " + '$' + "json\n";
      text += " *        @return string\n";
      text += " *\n";
      text += " *    JSONデータからCSVデータをダウンロードする\n";
      text += " *      window['json2csv']( " + '$' + "json, " + '$' + "filename );\n";
      text += " *        @param  json " + '$' + "json\n";
      text += " *        @param  string " + '$' + "filename\n";
      console.log(text);
    },
    csv: (json) => {
      const rowMap = new Map(Object.entries(json[0]));
      const headerAry = Array.from(rowMap).map((keyValList) => keyValList[0]);
      return json2csv._convertToCSV(json, headerAry);
    },
    download: (data, name) => {
      const blob = new Blob([data], { type: "text/csv" });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.setAttribute("href", url);
      a.setAttribute("download", `${name}.csv`);
      a.click();
      a.remove();
    },
    _convertToCSV: (data, headerAry) => {
      const headerStr = headerAry.join(",");
      const replacer = (_, value) => value ?? "";
      const rowItems = data.map((row) => headerAry.map((fieldName) => JSON.stringify(row[fieldName], replacer)).join(","));
      return [...rowItems].join("\r\n");
    },
  };
  window['json2csv'] = function (method){
    if( json2csv[method] ) return json2csv[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    else if( typeof method === 'object' || !method) return json2csv.construct.apply( this, arguments );
    else $.error('Method' + method + ' does not exist on json2csv');
  };

})();