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

const getKelime = async (key) => {
  console.log(key);
  const response = await axios.get(
    `https://api.diziyleogren.com/api/WordList/GetPublicList?uniqueKey=${key}`
  );
  return response.data;
};

const serve2 = async () => {
  let data = [];
  const keylist = ['ilk1000', 'ilk2000', 'ilk3000', 'ilk4000', 'ilk5000'];
  /* 
    Delay logic moved inside the loop sequentially. 
    Creating a promise-based delay helper. 
  */
  const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

  for (const key of keylist) {
    await delay(10000);
    const kelime = await getKelime(key);
    for (const item of kelime.words) {
      data.push({
        id: item.id,
        phrase: item.phrase,
        mean: item.mean,
        synonyms: item.synonyms,
        definition: item.definition,
        sampleSentence: item.sampleSentence,
        difficulty: item.difficulty,
      });
    }
  }

  fs.writeFileSync('data.json', JSON.stringify(data));
};

const serve = () => {
  const datas = fs.readFileSync('data.json');
  const data = JSON.parse(datas);
  console.log(data);
};

serve();
