import React from "react";
import Head from "next/head";
import Image from "next/image";
import styles from "../styles/Home.module.css";
import testStyles from "../styles/test.module.sass";
import AutoGallery from "../components/AutoGallery";
import GitGallery from "../components/GitGallery";
import RepoSummary from "../components/RepoSummary";

export default function Home(props) {
  return (
    <div className={styles.container}>
      <Head>
        <title>AcerecA.net</title>
        <meta name="description" content="Patricks Homepage" />
        <link rel="icon" href="/ace_logo.png" />
      </Head>

      <main className={styles.main}>
        <h1 className={styles.title}>Welcome, i&apos;m Patrick</h1>

        <p className={styles.description}>and this is what i do:</p>

        <AutoGallery />
        <RepoSummary {...props} />
        <GitGallery {...props} />
      </main>

      <footer className={styles.footer}>© 2022 Patrick Nisblé</footer>
    </div>
  );
}
export async function getStaticProps(context) {
  //Stats
  var stats = {
    languages: {},
  };
  //Gitea
  var giteaResp = await fetch("https://git.acereca.net/api/v1/repos/search");
  const publicGiteaRepos = await giteaResp.json();

  for (const repo of publicGiteaRepos.data) {
    var resp = await fetch(
      "https://git.acereca.net/api/v1/repos/" + repo.full_name + "/languages"
    );
    var dat = await resp.json();
    for (const lang in dat) {
      stats.languages[lang] = dat[lang] + (stats.languages[lang] || 0);
    }
  }

  // const sortable = Object.entries(stats.languages)
  // .sort(([, a], [, b]) => a - b)
  // .reduce((r, [k, v]) => ({ ...r, [k]: v }), {});

  // GitHub
  try {
    var githubResp = await fetch("https://api.github.com/users/acereca/repos", {
      headers: new Headers({
        Accept: "application/vnd.github.v3+json",
      }),
    });
    // console.log(githubResp);

    var publicGithubRepos = await githubResp.json();
  } catch (error) {
    console.warn(error);
  }

  for (const repo of publicGithubRepos) {
    var resp = await fetch(
      "https://api.github.com/repos/" + repo.full_name + "/languages",
      {
        headers: new Headers({
          Accept: "application/vnd.github.v3+json",
        }),
      }
    );
    var dat = await resp.json();
    for (const lang in dat) {
      stats.languages[lang] = dat[lang] + (stats.languages[lang] || 0);
    }
  }
  // console.log(publicGithubRepos);

  return {
    props: {
      stats: stats,
      publicGiteaRepos: publicGiteaRepos.data,
      publicGithubRepos: publicGithubRepos,
    },
  };
}
