import BasicPage from "../../components/basic-page";
import WCard from "../../components/werefox-card";
import TCard from "../../components/testimonial-card";
import axios from "axios";

// Async functions to grab user avatars server-side

export const getIcon = async ({ json, name }) =>
  await axios.get(json).then(
    ({ data }) => [name, data["icon"]["url"]],
    (error) => {
      console.log(error);
      return [name, null];
    }
  );

export const getStaticProps = async () => {
  const fs = require("fs");
  const yaml = require("js-yaml");
  let TESTIMONIALS = {};

  try {
    let fileContent = fs.readFileSync("./data/testimonials.yml", "utf8");
    TESTIMONIALS = yaml.load(fileContent);
  } catch (e) {
    console.log(e);
  }
  const promises = Object.entries(TESTIMONIALS).map(([name, { json }]) =>
    getIcon({ name, json })
  );
  const iconUrls = await Promise.all(promises);
  return {
    props: {
      iconUrls: iconUrls.reduce(
        (acc, [name, url]) => ({ ...acc, [name]: url }),
        {}
      ),
      TESTIMONIALS,
    },
  };
};

export default function Testimonials({ iconUrls, TESTIMONIALS }) {
  return (
    <BasicPage page_title="Werefox Testimonials" card_title="Testimonials!">
      <WCard
        innerText={`Sometimes, people say some nice things about me. Here are some
        examples!`}
      >
        {Object.keys(TESTIMONIALS).map((user) => (
          <TCard
            key={TESTIMONIALS[user].url}
            src={iconUrls[user]}
            alt={`${user}'s Avatar`}
            url={TESTIMONIALS[user].url}
            user={user}
            innerText={TESTIMONIALS[user].content}
          />
        ))}
      </WCard>
    </BasicPage>
  );
}
