import App, {AppProps} from 'next/app';
import {SessionProvider} from "next-auth/react";
import {config, library} from "@fortawesome/fontawesome-svg-core";
import '@fortawesome/fontawesome-svg-core/styles.css';
import {
  faBagShopping,
  faChalkboardUser,
  faChevronDown,
  faChevronUp,
  faGraduationCap,
  faGuitar,
  faLinesLeaning,
  faMagnifyingGlass,
  faRightToBracket,
  faScrewdriverWrench,
  faTabletScreenButton,
  faUserPlus
} from "@fortawesome/free-solid-svg-icons";
import axios from "axios";
import delve from 'dlv';
import {ThemeProvider} from "next-themes";

import {wrapper} from "../store/store";

import {environment} from "../environments/environment";
import './styles.css';

config.autoAddCss = false;

library.add(faRightToBracket);
library.add(faUserPlus);
library.add(faBagShopping);
library.add(faTabletScreenButton);
library.add(faGraduationCap);
library.add(faChalkboardUser);
library.add(faLinesLeaning);
library.add(faGuitar);
library.add(faScrewdriverWrench);
library.add(faChevronDown);
library.add(faChevronUp);
library.add(faMagnifyingGlass);

interface CustomAppProps extends AppProps {
  menuHeader: object[],
  menuFooter: object[],
  page: object,
  seo: object,
}

const getPageMetadata = async (path) => {
  try {
    if (path === '/_error') {
      throw 'page error';
    }
    console.log(path);
    return await axios.get(`${environment.strapiApiUrl}/pages?filters[slug]=${path === '/' ? 'home' : path.slice(1, path.length)}&populate=deep`);
  } catch (e) {
    console.error(e);
    return Promise.resolve({});
  }
}

const getCategoryMetadata = async (categorySlug) => {
  try {
    return await axios.get(`${environment.strapiApiUrl}/categories?filters[slug]=${categorySlug}&populate=deep`);
  } catch (e) {
    console.error(e);
    return Promise.resolve({});
  }
}

const getPostMetadata = async (postSlug) => {
  try {
    return await axios.get(`${environment.strapiApiUrl}/articles?filters[slug]=${postSlug}&populate=deep`);
  } catch (e) {
    console.error(e);
    return Promise.resolve({});
  }
}


const CustomApp = ({Component, pageProps: {session, ...pageProps}, menuFooter, menuHeader, seo}: CustomAppProps) => {
  pageProps = {...pageProps, menuFooter, menuHeader, seo};
  return (
    <SessionProvider session={session}>
      <ThemeProvider enableSystem={true}
                     attribute="class">
        <Component {...pageProps} />
      </ThemeProvider>
    </SessionProvider>
  );
}

CustomApp.getInitialProps = async (context) => {
  const appProps = await App.getInitialProps(context);
  const path = context.router.pathname;
  const menuHeader = await axios.get(`${environment.strapiApiUrl}/menus/1?nested&populate=deep`);
  const menuFooter = await axios.get(`${environment.strapiApiUrl}/menus/2?nested&populate=deep`);
  let page = null;

  if (context.ctx.query.category_slug && !context.ctx.query.post_slug) {
    page = await getCategoryMetadata(context.ctx.query.category_slug);
  } else if (context.ctx.query.category_slug && context.ctx.query.post_slug) {
    page = await getPostMetadata(context.ctx.query.post_slug);
  } else if (!context.ctx.query.category_slug && !context.ctx.query.post_slug) {
    page = await getPageMetadata(path);
  }

  return {
    ...appProps,
    menuHeader: delve(menuHeader, 'data.data.attributes.items.data', []),
    menuFooter: delve(menuFooter, 'data.data.attributes.items.data', []),
    page: delve(page, "data.data.0.attributes", {}),
    seo: delve(page, "data.data.0.attributes.seo", {})
  }
}

export default wrapper.withRedux(CustomApp);
