import React, { useContext, useEffect } from 'react';
import { useRouter } from 'next/router';
//import { GetServerSideProps } from 'next';
import Head from 'src/components/core/head';
import { getPagebySlug, getAllPages, getSearchEngineIndexing } from 'services/wpgraphql';
import { Page } from 'src/components/layouts/containers';
import { PreintakeCta, PreintakeCtaProps } from 'src/components/blocks';
import { BlockArray } from 'src/components/core/blockArray';
import { ComponentRenderer } from 'utils/componentMap';
import { LanguageContext } from 'context/languageContext';

import type { GetStaticProps, GetStaticPaths } from 'next';

interface PageProps {
    slug: string,
    sections: Array<any>;
    showPreintake: boolean;
    preintakeData: PreintakeCtaProps;
    errorCode: number;
    shouldIndex?: string;
}

// Format slug to be Camel case.
function formatSlug(slg: string) {
  
  // First letter is capitalized.
  let newSlug = slg[0].toUpperCase() + slg.substring(1);
  
  for (let i = 0; i < slg.length; i++) {
    if(slg.charAt(i) == '-') {
      newSlug = newSlug.substring(0,i) + " " + newSlug[i+1].toUpperCase() + newSlug.substring(i+2);
    }
  }
  
  return newSlug;
}

/**
 * Loop through page section blocks and display them
 * 
 * @since v1.0.0
 * @param param0 
 * @returns Page element
 */
export const Content: React.FC<PageProps> = ({ slug, sections, showPreintake, preintakeData, errorCode, shouldIndex }): JSX.Element => {
    const router = useRouter();
    const { language } = useContext(LanguageContext);
    //const slug = router?.query?.slug as string;

    const formattedSlug = formatSlug(slug);

  useEffect(() => {
    if (errorCode) {
      router.push('/');
    }
  });

  return (
    <Page>
      <Head title={formattedSlug} shouldIndex={shouldIndex} />
      <BlockArray
        items={sections}
        renderItem={(item, index) => <React.Fragment key={index}> {ComponentRenderer(item, language)}</React.Fragment>}
      />
      {showPreintake && <PreintakeCta {...preintakeData} language={language} />}
    </Page>
  );
};

/*
export const getServerSideProps: GetServerSideProps = async ({ query }) => {
    const { data } = await getPagebySlug(query.slug as string);

    const sections = data?.page?.sections?.layout;
    const errorCode = sections ? null : 404;

    if (errorCode) {
        return {
            props: {
                errorCode,
            },
        };
    }

    const {"data": {"additionalSettings": {"searchEngineIndexing": shouldIndex}}} = await getSearchEngineIndexing();

    //data.page.sections.layout.forEach((i) => { console.log(i.content)});

    return {
        props: {
            sections: data.page.sections.layout,
            showPreintake: data.page.sections.showPreintake,
            preintakeData: data.post.acf_preintakeCta,
            shouldIndex: shouldIndex
        },
    };
};
*/

export const getStaticProps: GetStaticProps = async (props) => {
    const slug = props?.params?.slug;
    //const { language } = useContext(LanguageContext);

    const { data } = await getPagebySlug(slug as string);
    const {"data": {"additionalSettings": {"searchEngineIndexing": shouldIndex}}} = await getSearchEngineIndexing();

    const sections = data?.page?.sections?.layout;
    const errorCode = sections ? null : 404;

    if (errorCode) {
        return {
            props: {
                errorCode,
            },
        };
    }

    return {
        props: {
            slug: slug,
            //language: language,
            sections: data.page.sections.layout,
            showPreintake: data.page.sections.showPreintake,
            preintakeData: data.post.acf_preintakeCta,
            shouldIndex: shouldIndex
        },
        revalidate: 5,
    };
};

export const getStaticPaths: GetStaticPaths = async () => {

    const { data } = await getAllPages();


    let paths = data.pages.nodes.map((page: any) => (
        { params: { slug: page.slug }, locale: "en" }
    ));

    paths = paths.concat(
        data.pages.nodes.map((page: any) => (
            { params: { slug: page.slug }, locale: "es"}
        ))
    );


    console.log(paths);

    return {
        paths: paths,
        fallback: "blocking", // false or "blocking"
    }
};

//export const dynamic = 'force-dynamic';
//export const revalidate = 0;

export default Content;