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);
      if (name == "Dax") {
        return [name, `/images/Dax.jpeg`];
      }
      return [name, null];
    }
  );

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

  try {
    let fileContent = fs.readFileSync("./data/pages/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 }) {
  console.log(iconUrls)
  return (
    <BasicPage
      page_title="Werefox Testimonials"
      card_title="Testimonials!"
      page_button_title="Take me back home!"
    >
      <WCard
        title={`Sometimes, people say some nice things about me. Here are some
        examples!`}
      >
        <div className="p-2 space-y-4">
          {Object.keys(TESTIMONIALS).map((user) => (
            <TCard
              key={TESTIMONIALS[user].url}
              src={
                Boolean(iconUrls[user]) ? iconUrls[user] : `/images/${user}.png`
              }
              alt={`${user}'s Avatar`}
              url={TESTIMONIALS[user].url}
              user={user}
              innerText={TESTIMONIALS[user].content}
            />
          ))}
        </div>
      </WCard>
    </BasicPage>
  );
}
