import readXlsxFile from 'read-excel-file';

async function convertFileFromStream(stream, filterColumnNames = ['what', 'deliveryscope']) {
  const toFilterValue = x => x.toLowerCase().replace(/\s+/g, '');
  const sheets = await readXlsxFile(stream, { getSheets: true });
  let dataRows = [];
  let sheetsData = await Promise.all(
    sheets.map(async sheet => {
      return await readXlsxFile(stream, { sheet: sheet.name });
    }),
  );

  let types = {};
  sheetsData.forEach(sheetData => {
    const firstRow = sheetData.shift().map(x => toFilterValue(x));
    // Set up column for adding options
    firstRow.forEach((col, i) => {
      if (typeof types[col] === 'undefined' && filterColumnNames.includes(col)) {
        types[col] = [];
      }
    });
    sheetData.forEach((row, rowindex) => {
      const dataRow = {};
      firstRow.forEach(async (col, i) => {
        const rowVal = row[i];
        dataRow[col] = rowVal;
        // Add to types options
        if (filterColumnNames.includes(col)) {
          const filterVal = toFilterValue(rowVal);
          dataRow[col] = filterVal;
          if (!types[col].includes(filterVal)) {
            types[col].push(filterVal);
          }
        }
      });
      dataRows.push(dataRow);
    });
  });

  const fileData = {
    types: types,
    data: dataRows,
  };
  return fileData;
}

export { convertFileFromStream };
