const ExcelJS = require('exceljs');
const workbook = new ExcelJS.Workbook();
const fs = require('fs');

const HEADER_ROW_INDEX = 1;
const CATEGORY_COL_INDEX = 7;
var output = [];
var all_categories = [];
var categories_found = [];

(async () => {
  await workbook.xlsx.readFile('lessons.xlsx');
  let worksheets = workbook.worksheets;
  for (const ws of worksheets) {
    const header_row = ws.getRow(HEADER_ROW_INDEX);
    const last_row = ws.lastRow;

    for (let i = HEADER_ROW_INDEX + 1; i <= last_row._number; i++) {
      if (categories_found.indexOf(ws.getRow(i).getCell(CATEGORY_COL_INDEX).value) === -1) {
        categories_found.push(ws.getRow(i).getCell(CATEGORY_COL_INDEX).value);
      }
    }

    for (const cat_name of categories_found) {
      let words = [];
      for (let i = HEADER_ROW_INDEX + 1; i <= last_row._number; i++) {
        if (ws.getRow(i).getCell(CATEGORY_COL_INDEX).value === cat_name) {
          let word = ws.getRow(i).getCell(1).value.trim();
          let word_c = ws.getRow(i).getCell(2).value.trim();
          let sample_e = ws.getRow(i).getCell(3).value.trim();
          let sample_c = ws.getRow(i).getCell(4).value.trim();
          let sound = `/data/Lesson/sounds/${ws.getRow(i).getCell(5).value}`;
          let image = `/data/Lesson/images/${ws.getRow(i).getCell(6).value}`;

          words.push({ word, word_c, sample_e, sample_c, sound, image });
        }
      }

      let cat_image = `/data/Lesson/images/${cat_name.toLowerCase()}.jpg`;

      all_categories.push({
        //
        cat_name,
        cat_image,
        content: words
      });
    }

    output.push({
      name: ws.name,
      path: ws.name,
      content: all_categories
    });
  }

  fs.writeFileSync('output.json', JSON.stringify(output, null, 2));
})();
