const fs = require('fs');
const path = require('path');

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

const HEADER_ROW_INDEX = 1;
//
const QUESTION_NUM_COL_IDX = 1;
const FH_COL_IDX = 2;
const SH_COL_IDX = 3;
const ANS_COL_IDX = 4;
const OPT1_COL_IDX = 5;
const OPT2_COL_IDX = 6;
const OPT3_COL_IDX = 7;
// CAT_NAME_IDX
const QUIZ_NUM_COL_IDX = 8;

const TOOLS_HOME = path.resolve(__dirname);
const PROJ_HOME = path.resolve(path.join(TOOLS_HOME, '..', '..'));
const PUBLIC_DATA = path.resolve(path.join(PROJ_HOME, 'public', 'data'));
const QUIZ_HOME = path.resolve(path.join(PUBLIC_DATA, 'Quiz'));
const QUIZ_CONNECTIVE_REVISION_HOME = path.resolve(path.join(QUIZ_HOME, 'ConnectivesRevision'));
const OUTPUT_JSON_PATH = path.resolve(path.join(QUIZ_CONNECTIVE_REVISION_HOME, 'content.json'));

var output = [];
var all_categories = [];
var categories_found = [];

//
function checkFileExist(file_path) {
  if (!fs.existsSync(getUnderscoreFilename(file_path))) {
    throw new Error(`resources file not found: ${file_path}`);
  }
  return;
}

function getCellValue(cell) {
  return cell ? cell.result || cell.value : '';
}

function getUnderscoreFilename(file_name) {
  return file_name.replace(/\s/g, '_');
}

function findLastRowIdx(ws) {
  for (let i = 1; i < 130; i++) {
    let test = getCellValue(ws.getRow(i).getCell(1));

    if (!test || test.toString().trim() === '') {
      return i - 1;
    }
  }
  return 3000;
}

(async () => {
  try {
    await workbook.xlsx.readFile('main.xlsx');
    let worksheets = workbook.worksheets;

    // gen output
    for (const ws of worksheets) {
      const first_data_row_idx = HEADER_ROW_INDEX + 1;
      const last_data_row_idx = findLastRowIdx(ws);
      //

      for (let i = first_data_row_idx; i <= last_data_row_idx; i++) {
        if (ws.getRow(i).getCell(QUIZ_NUM_COL_IDX).value) {
          if (categories_found.indexOf(ws.getRow(i).getCell(QUIZ_NUM_COL_IDX).value) === -1) {
            categories_found.push(ws.getRow(i).getCell(QUIZ_NUM_COL_IDX).value);
          }
        }
      }
    }

    for (const ws of worksheets) {
      const first_data_row_idx = HEADER_ROW_INDEX + 1;
      const last_data_row_idx = findLastRowIdx(ws);

      for (const cat_name of categories_found) {
        let questions = [];
        // let cat_image = '';
        for (let i = first_data_row_idx; i <= last_data_row_idx; i++) {
          let quiz_num = getCellValue(ws.getRow(i).getCell(QUIZ_NUM_COL_IDX));
          if (cat_name.toString() == quiz_num.toString()) {
            //
            let question_fh = getCellValue(ws.getRow(i).getCell(FH_COL_IDX)) || '';
            let question_sh = getCellValue(ws.getRow(i).getCell(SH_COL_IDX)) || '';
            let modal_ans = getCellValue(ws.getRow(i).getCell(ANS_COL_IDX));
            let opt1 = getCellValue(ws.getRow(i).getCell(OPT1_COL_IDX));
            let opt2 = getCellValue(ws.getRow(i).getCell(OPT2_COL_IDX));
            let opt3 = getCellValue(ws.getRow(i).getCell(OPT3_COL_IDX));

            questions.push({
              question_fh,
              question_sh,
              modal_ans,
              options: [opt1, opt2, opt3],
              quiz_num
              //
            });
          }
        }

        all_categories.push({
          //
          cat_name: cat_name.toString(),
          content: questions,
          init_ans: ['D', 'E', 'F']
        });
      }

      output = all_categories;
    }

    console.log('writing output json file...');
    console.log(OUTPUT_JSON_PATH);
    fs.writeFileSync(OUTPUT_JSON_PATH, JSON.stringify(output, null));

    console.log('done');
  } catch (error) {
    console.log(error);
    process.exit(1);
  }
})();
