function prePostCsvMap(version) {
  let courseDataClone = versionedCourseData(version);

  delete courseDataClone.PreAacademyComplete
  delete courseDataClone.PostAacademyComplete

  const courseData = {}

  Object.keys(courseDataClone).forEach(key => {
    courseData[key] = key;
  });

  return  {
    "academy": "academy",
    "email": "email_address",
    "createdAt": "created_at",
    "status": "status",
    ...courseData,
  }
}

function convertToCsv(users) {
  let array = typeof users != 'object' ? JSON.parse(users) : users;
  let str = '';

  for (var i = 0; i < array.length; i++) {
    var line = '';
    for (var fieldName in array[i]) {
      if (line != '') line += ','

      var val  = array[i][fieldName]

      if (i > 0 && typeof val === "string") {
        line += `\"${val.replace(/\"/g, "'")}\"`
      }
      else {
        line += `\"${val}\"`;
      }
    }

    str += line + '\r\n';
  }

  return str;
}

async function exportCsv(elem) {
  const version = elem.dataset.version;
  const snapshot = await db.collection('users').where('moduleVersion', '==', version).get();
  const users = snapshot.docs.map(doc => doc.data());
  const csvRows = [];
  const csvMapClone = prePostCsvMap(version);

  console.log("# of Users' data: " , users.length)

  users.forEach(user => {
    const userRow = {}
    Object.keys(csvMapClone).forEach(attr => {
      if (attr == "status") {
        userRow[attr] = buildStatus(user);
        return;
      }
      if (typeof user[attr] == "undefined" || user[attr] === null) {
        userRow[attr] = "";
        return;
      }
      if (attr == "createdAt") {
        // userRow[attr] = user[attr].toDate().toDateString();
        // userRow[attr] = user[attr].toDate().toISOString().split('T')[0]; // e.g 2021-05-26
        userRow[attr] = user[attr].toDate().toLocaleDateString("en-US"); // e.g. 3/12/2021
        return;
      }

      userRow[attr] = user[attr];
    });
    csvRows.push(userRow);
  });

  if (csvMapClone) {
    csvRows.unshift(csvMapClone);
  }

  const jsonObject = JSON.stringify(csvRows);
  const csv = await this.convertToCsv(jsonObject);
  const timestamp = new Date().toJSON().replace(/:/g, '.');
  const exportedFilename =  'pre-post' + `-v${version}-data-` + timestamp + '.csv';
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });

  if (navigator.msSaveBlob) { // IE 10+
    navigator.msSaveBlob(blob, exportedFilename);
  }
  else {
    var link = document.createElement("a");
    if (link.download !== undefined) { // feature detection
      // Browsers that support HTML5 download attribute
      var url = URL.createObjectURL(blob);
      link.setAttribute("href", url);
      link.setAttribute("download", exportedFilename);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }
}

function buildStatus(user) {
  const preStatus = isPretestComplete(user);
  const postStatus = isPosttestComplete(user);

  if (!preStatus && !postStatus) { return ""; }
  if (preStatus && !postStatus) { return "PRE only"; }
  if (preStatus && postStatus) { return "Pre/post"; }
}
