import HomePage from "../components/home-page";
import IDBlock from "../components/identity-block";
import WCard from "../components/werefox-card";
import ICard from "../components/introduction-card";
import PBlock from "../components/page-block";

export function parseEmoji(TEXTBLOCK) {
  const emoji_pattern = new RegExp(/(:[A-Za-z_-]+:)/, "g");
  let emoji = [];
  Array.from(emoji_pattern[Symbol.matchAll](TEXTBLOCK.intro)).forEach(
    (e, i) => {
      emoji.push(e[0]);
    }
  );
  return emoji;
}

// An object listing pages folks can visit
export async function getStaticProps() {
  const fs = require("fs");
  const yaml = require("js-yaml");
  let IDENTITIES = {};
  let INTRODUCTION = {};
  let PAGES = {};
  let PARTNERS = {};
  let emoji_paths = {};

  try {
    let fileContent = fs.readFileSync("./data/identities.yml", "utf8");
    IDENTITIES = yaml.load(fileContent);
    fileContent = fs.readFileSync("./data/introduction.yml", "utf8");
    INTRODUCTION = yaml.load(fileContent);
    fileContent = fs.readFileSync("./data/pages.yml", "utf8");
    PAGES = yaml.load(fileContent);
    fileContent = fs.readFileSync("./data/identities/partners.yml", "utf8");
    PARTNERS = yaml.load(fileContent);
    let emoji = parseEmoji(INTRODUCTION);
    emoji.forEach((e, i) => {
      if (fs.existsSync(`./public/emoji/${e}.svg`)) {
        emoji_paths[e] = `/emoji/${e}.svg`;
      } else if (fs.existsSync(`./public/emoji/${e}.png`)) {
        emoji_paths[e] = `/emoji/${e}.png`;
      } else {
        emoji_paths[e] = `/emoji/:aliceweh:.png`;
      }
    });
  } catch (e) {
    console.log(e);
  }
  return {
    props: {
      IDENTITIES,
      INTRODUCTION,
      PAGES,
      PARTNERS,
      emoji_paths,
    },
  };
}

export default function Home({
  IDENTITIES,
  INTRODUCTION,
  PAGES,
  PARTNERS,
  emoji_paths,
}) {
  const partnerslen = PARTNERS ? Object.keys(PARTNERS).length : 0;
  return (
    <HomePage page_title="About A Werefox" card_title="Hi! I'm Alice Werefox!">
      <WCard title="Basic Info">
        <IDBlock identities={IDENTITIES} partners={partnerslen} />
      </WCard>
      <WCard title="Welcome to my little info site!">
        <ICard introduction={INTRODUCTION.intro} emoji_paths={emoji_paths} />
      </WCard>
      <WCard title="Neat Pages!">
        <PBlock pages={PAGES} />
      </WCard>
    </HomePage>
  );
}
