async function fetchData(log, tpl) {
  var log = document.getElementById("log");

  var server_address = `techhub.social`;

  // const response = await fetch('json/posts.json');

  const response = await fetch(
    `https://${server_address}/api/v1/accounts/111518136987654656/statuses`,
  );

  const data = await response.json();

  data.forEach((obj) => {
    let post_tpl = tpl;
    var media_link = "";
    Object.entries(obj).forEach(([key, value]) => {
      if (key == "id") {
        post_tpl = post_tpl.replace(/{post_id}/g, `${value}`);
      }

      if (key == "account") {
        post_tpl = post_tpl.replace(/{id}/g, `${value.id}`);
        post_tpl = post_tpl.replace(/{name}/g, `${value.display_name}`);
        post_tpl = post_tpl.replace(/{server_address}/g, `${server_address}`);
        post_tpl = post_tpl.replace(
          /{account_name}/g,
          `<a href="https://${server_address}/@${value.username}" target="_blank">@${value.username}@${server_address}</a>`,
        );
        // post_tpl = post_tpl.replace('{avatar}', `<img src="${value.avatar}" alt="${value.username}'s Avatar" style="width:48px;height:48px;">`);
        post_tpl = post_tpl.replace(/{avatar}/g, `${value.avatar}`);
        post_tpl = post_tpl.replace(/{profile_link}/g, `${value.url}`);
      }

      if (key == "content") {
        let text = value;

        let youtube_frame_arr = [];
        let spl_arr = text.split('"');
        let youtube_links_start = [
          "https://www.youtube.com/watch?v=",
          "https://youtube.com/watch?v=",
          "https://youtube.com/v/",
          "https://m.youtube.com/watch?v=",
          "https://m.youtube.com/v/",
        ];

        for (let i = 0; i < spl_arr.length; i++) {
          youtube_links_start.forEach((youtube_link_start) => {
            if (spl_arr[i].indexOf(youtube_link_start) === 0) {
              let id = spl_arr[i].replace(youtube_link_start, "");
              let text_frame = `<iframe class="youtube-video" src="https://www.youtube.com/embed/${id}?rel=0" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>`;
              youtube_frame_arr.push(text_frame);
            }
          });
        }

        youtube_frame_arr.forEach(function (elem) {
          text += elem;
        });

        // let regular = /<a (.*?)https:\/\/www.youtube.com\/watch\?v\=(.*?)>(.*?)<\/a>/g;
        // text = text.replace(regular, '');

        value = text;

        post_tpl = post_tpl.replace("{content}", `${value}`);
      }

      if (key == "media_attachments") {
        value.forEach((obj1) => {
          Object.entries(obj1).forEach(([k, v]) => {
            if (k == "preview_url") {
              media_link += `<img src="${v}" full_src="${obj1.url}" class="fullscreen" onclick="showFullscreenImage(this);">`;
            }
          });
        });

        post_tpl = post_tpl.replace("{media_attachments}", `${media_link}`);
      }

      if (key == "created_at") {
        post_tpl = post_tpl.replace(/{created_at}/g, `${value}`);
      }

      if (key == "created_at") {
        var isoDate = `${value}`;
        var d = new Date(isoDate);
        //var datetime_ =  d.toLocaleString('en-GB', { hour12: false, timeZone: "Asia/Yekaterinburg" });
        var datetime_ = d.toLocaleString("ru-RU", {
          hour12: false,
          timeZone: "Asia/Yekaterinburg",
        });

        post_tpl = post_tpl.replace(/{created_at_show}/g, `${datetime_}`);
      }

      if (key == "edited_at") {
        post_tpl = post_tpl.replace(/{edited_at}/g, `${value}`);
      }

      if (key == "favorites_count") {
        post_tpl = post_tpl.replace(/{favorites_count}/g, `${value}`);
      }

      if (key == "replies_count") {
        post_tpl = post_tpl.replace(/{replies_count}/g, `${value}`);
      }

      if (key == "reblogs_count") {
        post_tpl = post_tpl.replace(/{reblogs_count}/g, `${value}`);
      }

      // log.innerHTML  = log.innerHTML + `${key} ${value}` + '<br>';
    });
    log.innerHTML += `${post_tpl}<br>`;
  });
}
async function openInNewTab(url) {
  window.open(url, "_blank").focus();
}

async function getLog() {
  let log = document.getElementById("log");
  if (log == null) {
    setTimeout(getLog, 1000);
  } else {
    getMastodonPage();
  }
}
async function getMastodonPage() {
  let log = document.getElementById("log");

  let tplUrl = "/json/mastodon-tpl.html";
  let response = await fetch(tplUrl);
  var tpl = "";

  log.innerHTML = "";

  const controller = new AbortController();
  const signal = controller.signal;

  // Cancel the fetch request in 500ms
  setTimeout(() => controller.abort(), 500);

  try {
    const response = await fetch(tplUrl, { signal });
    tpl = await response.text();
  } catch (error) {
    // DOMException: The user aborted a request.
    console.log("Error: ", error);
    log.innerHTML = "<p>1) Ой всё сломалось :(</p>";
  }

  if (!tpl) {
    log.innerHTML = "<p>2) Ой всё сломалось :(</p>";
  }

  fetchData(log, tpl);
}

let query = window.location.pathname;

if (query == "/" || query == "/news") {
  getLog();
}
