function inlineContent(str){
  let data = str.split("<br>");
  let content = "";
  for (let line of data){
    content += line + '\n';
  }
  return content
}

function creditsContent(str){
  let data = str.split("<br>")
  let credits = data[0].split(" - ");
  return {
    track: credits[0],
    artist: credits[1]
  }
}

export async function loadAudioData() {
  const audioRes = await fetch('/DATA/audioData.json');
  const aData = await audioRes.json();
  //console.log("MUSIC :", aData);
  const res = await fetch("https://pouet.drags-nerds.net/api/v1/timelines/public?local=true&limit=40");

  if(!res.ok) throw new Error(`Server responded with ${res.status} ${res.statusText}`);

  const pouets = await res.json();
  const filtered = pouets.filter(p => aData.some(user => p.account.username === user || p.reblog?.account.username === user.name));
  //console.log(filtered);
  const files = {};
  for (const user of aData) {
    files[user] = [];
  }

  let audioFiles = [];

  for (const pouet of filtered){
    let selectedPouet;
    if (pouet.reblog){
      selectedPouet = pouet.reblog;
    } else {
      selectedPouet = pouet;
    }
    //ignorer les PJ autres que audio
    if (selectedPouet.media_attachments?.length > 0 &&
        !selectedPouet.media_attachments[0].type.includes('audio')) {
      continue;
    }

    if(selectedPouet.media_attachments?.length > 0){
        let credits = creditsContent(selectedPouet.content);
      let entry = {
        track: credits.track,
        artist: credits.artist,
        src: selectedPouet.media_attachments[0].url
      }
      audioFiles.push(entry);
    }
  }

  //console.log(audioFiles);
  return audioFiles
}
