"use strict";
// read './APP_Vocab_List.xlsx'
// the first row is the header
// coloumns name are 'Word', 'CHI_trans', 'ENG_Sample_sentence', 'CHI_trans_sentence', 'mp3 filename', 'jpg filename', 'Category'
// convert name to 'word', 'word_c', 'sample_e', 'sample_c', 'sound', 'image', 'category'
// for a json array row by row
// write output to content.json

const PUBLIC_ASSETS_HOME = "/data/Lesson";
const PUBLIC_IMAGE_HOME = `${PUBLIC_ASSETS_HOME}/images`;
const PUBLIC_SOUND_HOME = `${PUBLIC_ASSETS_HOME}/sounds`;

const xlsx = require("xlsx");
const fs = require("fs");
const path = require("path");
const workbook = xlsx.readFile("./APP_Vocab_List.xlsx");

const worksheet = workbook.Sheets["Sheet1"];

const whole_sheet = xlsx.utils.sheet_to_json(worksheet, { header: 1 });
const sheet_without_header = whole_sheet.slice(1);

const json_step1 = sheet_without_header.map((row, i) => {
  const saintized_row = row.map((r) => r.trim());

  return {
    word: saintized_row[0],
    word_c: saintized_row[1],
    sample_e: saintized_row[2],
    sample_c: saintized_row[3],
    sound: saintized_row[4],
    image: saintized_row[5],
    category: saintized_row[6],
    cat_image: saintized_row[7],
  };
});

const json_step2 = json_step1.map((r) => {
  return {
    word: r.word,
    word_c: r.word_c,
    sample_e: r.sample_e,
    sample_c: r.sample_c,
    sound: path.join(PUBLIC_SOUND_HOME, r.sound),
    image: path.join(PUBLIC_IMAGE_HOME, r.image),
    category: r.category,
    cat_image: path.join(PUBLIC_IMAGE_HOME, r.cat_image),
  };
});

var json_categories = [...new Set(json_step2.map((r) => r.category))].map(
  (cat) => {
    return {
      cat_name: cat,
      cat_image: json_step2.filter((r) => r.category == cat)[0].cat_image,
      content: json_step2
        .filter((r) => r.category == cat)
        .map((r) => {
          delete r.cat_image;
          delete r.category;
          return r;
        }),
      //
    };
  }
);

var json_output = [
  {
    name: "vocabulary",
    path: "vocabulary",
    content: json_categories,
  },
];

fs.writeFileSync("content.json", JSON.stringify(json_output, null, 2));
