import * as React from "react";
import Layout from "../../components/Layout";
import { Translation, TranslationObjectType } from "../";
import { NextPage } from "next";
import fetch from "isomorphic-unfetch";

const Lang: NextPage<{
  translations: TranslationObjectType;
  defaultText: TranslationObjectType;
  languages: string[];
  lang: string;
}> = (props) => {
  return (
    <Layout languages={props.languages}>
      <div
        style={{
          display: "grid",
          gridAutoFlow: "column",
          paddingTop: "68px",
        }}
      >
        {props.lang ? (
          <Translation
            translation={props.translations}
            defaultText={props.defaultText}
            language={props.lang}
          />
        ) : (
          "Not a valid language"
        )}
      </div>
    </Layout>
  );
};

Lang.getInitialProps = async function (req) {
  const res = await fetch("http://localhost:8080/translations");
  const data = await res.json();

  const languages = Object.keys(data);
  const validLanguage = languages.includes(`${req.query.lang}.json`);

  const translations = validLanguage ? data[`${req.query.lang}.json`] : [];
  const defaultText = data["default.json"];
  const lang = validLanguage ? (req.query.lang as string) : "";

  return {
    translations,
    defaultText,
    languages,
    lang,
  };
};

export default Lang;
