// jsut iterate through all relevant data serverside instead of dealing with it client side
import fsPromises from 'fs/promises'
import path from 'path'
import ReadyOrNotMap from '../../interfaces/ReadyOrNot'

export default async function TobarApi(req: any, res: any) {
  try {
    // get list of all folders(maps) in the readyornot folder - maybe there is a cleaner way to do this?
    var fs = require('fs')
    var mapList = fs.readdirSync(path.join(process.cwd(), '/public/images/'), { withFileTypes: true })
                          .filter((dirent:any) => dirent.isDirectory())
                          .map((dirent:any) => dirent.name);

    // iterate through every map entry and extract the info
    let maps: ReadyOrNotMap[] = [];

    for (let i = 0; i < mapList.length; i++) {
      // get map data for the API request
      const filePathEmpire = path.join(process.cwd(), '/public/images/' + mapList[i] + '/info.json');
      const jsonDataEmpire = await fsPromises.readFile(filePathEmpire);
      let mapData = JSON.parse(jsonDataEmpire.toString());
      mapData.href = mapList[i];

      maps.push(mapData) ; 
    }

    res.status(200).json(maps);
  }
  catch (error) {
    console.log(error);
    res.status(500).json({ error: 'Error reading data' });
  }
}