function idAndDate(str){
  let data = str.split("T");
  let date = data[0].split("-");
  return {
    date: date[2] +'/'+ date[1],
    id: date[2] + date[1]
  }
}

function titleAndContent(str){
  let data = str.split(" :");
  let title = "NO_TITLE";
  if (data.length > 1){
    title = data[0];
  }
  let contentData = [""];
  if (data[1]){
    contentData = data[1].split('<br>').filter(e => e);
  }
  let content = "";
  let src = [];
  for(let line of contentData){
    if(line.includes('http')||line.includes('@')){
      let linkData = line.split("# ");
      //console.log(title, linkData);
      let linkNoFormat;
      if (linkData.includes('http')){
        linkNoFormat = linkData[1].split("\"");
      } else {
        linkNoFormat = linkData[0]
      }
      let url = "";
      for(let el of linkNoFormat){
        if(el.includes('http')){
          url = el;
          break
        } else if(el.includes('@')){
          url = 'mailto:' + el;
          break
        } else {
          continue
        }
      }
      src.push({
        caption: linkData[0],
        url: url
      })
    } else {
      content += line + '\n';
    }
  }
  return {
    title: title,
    content: content.split('/333/')[0],
    links: src,
  }
}

function exceptionKey(user, content){
  let data = content.split('/333/');
  let key = "";
  if (data.length > 1) key = data[1].split('<br>')[0];
  //console.log(key);
  if (key === "bm90X3dlYnNpdGVfY29udGVudA==" && user !=="drags_nerds") return true;
  if (user === "drags_nerds"){
    if(key != "c2VuZF9tZXNzYWdlX3RvX3dlYnNpdGU="){
      return true;
    }
  }
  return false;
}

export async function loadPeopleData() {
  const usernamesRes = await fetch('/DATA/peopleData.json');
  const pData = await usernamesRes.json();
  //console.log("USERS :", pData);
  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();
  //console.log("POUETS :" , pouets);
  const filtered = pouets.filter(p => pData.some(user => p.account.username === user.name || p.reblog?.account.username === user.name));
  //console.log("FILTERED :" , filtered);
  const files = {};
  for (const user of pData) {
    files[user.name] = [];
  }
  const description = {};
  for (const user of pData){
    const pouet = filtered.find(p => p.account.username === user.name || p.reblog?.account.username === user.name);
    if (pouet){
      description[user.name] = pouet.account.note;
    }
  }

  for (const pouet of filtered) {
    let selectedPouet;
    if(pouet.reblog){
      selectedPouet = pouet.reblog;
    } else {
      selectedPouet = pouet;
    }
    //console.log(selectedPouet);
    const username = selectedPouet.account.username;
    const displayName = selectedPouet.account.display_name;
    let infos = idAndDate(selectedPouet.created_at);
    let entry;
    //console.log(pouet);
    //ignorer autres que images
    if (selectedPouet.media_attachments?.length > 0 &&
        !pouet.media_attachments[0].type.includes('image')) {
      continue;
    }
    //ignorer réponses
    if (selectedPouet.in_reply_to_account_id) {
      continue;
    }
    //ignorer exceptions
    let exception = exceptionKey(username, selectedPouet.content);
    //console.log(exception)
    if(exception){
      continue;
    }

    if (selectedPouet.content.includes('http')) {
      let textInfos = titleAndContent(selectedPouet.content);
      entry = {
        id: 'link' + displayName + infos.id,
        date: infos.date,
        dateInfo: selectedPouet.created_at,
        type: "link",
        author: displayName,
        caption: textInfos.title + '.liens',
        links: textInfos.links,
        description: textInfos.content,
        isSelected: false
      };
    } else if (selectedPouet.media_attachments?.length > 0) {
          let textInfos = titleAndContent(selectedPouet.content);
          //console.log(pouet);
          entry = {
            id: 'img' + displayName + infos.id,
            date: infos.date,
            dateInfo: selectedPouet.created_at,
            type: "image",
            author: displayName,
            caption: textInfos.title + '.star',
            src: selectedPouet.media_attachments[0].url,
            alt: selectedPouet.media_attachments[0].description,
            description: textInfos.content,
            like: selectedPouet.favourites_count,
            isSelected: false
          }
    } else {
      let textInfos = titleAndContent(selectedPouet.content);
      entry = {
        id: 'txt' + displayName + infos.id,
        date: infos.date,
        dateInfo: selectedPouet.created_at,
        type: "text",
        author: displayName,
        caption: textInfos.title + '.msg',
        description: textInfos.content,
        isSelected: false
      };
    }
    files[username].push(entry);
  }

  const dragContent = pData.filter(user => user.folder === 0).map(user => (
    {
      type: "folder",
      caption: user.name + '.info',
      children: files[user.name],
      description: description[user.name],
      isSelected: false
  }));
  const nerdContent = pData.filter(user => user.folder === 1).map(user => (
    {
      type: "folder",
      caption: user.name + '.info',
      children: files[user.name],
      description: description[user.name],
      isSelected: false
  }));

  const otherContent = pData.filter(user => user.folder === 2).flatMap(user => files[user.name]);


  const sortedContent = [
    {
    type: "folder",
    caption : "Artistes Drags",
    description:"Pour en savoir plus sur nos artistes drags, c'est par ici !",
    children: dragContent,
    isSelected: false
    },
    {
    type: "folder",
    caption : "Artistes Nerds",
    description:"Pour en savoir plus sur nos artistes nerds, c'est par là !",
    children: nerdContent,
    isSelected: false
    },
    {
    type: "folder",
    caption : "Autres contenus",
    description:"Dans cette section, on place pleins de contenu, en vrac, \n sur nous, nos copaines, des trucs qu'on trouve cool, etc.",
    children: otherContent,
    isSelected: false
    }
  ];
  return sortedContent;
}
