import { mkdirSync, writeFileSync } from "fs";
import { join, resolve } from "path";
import * as rimraf from "rimraf";
import { Core, INavTree, ISection } from ".";
import { IContentPageProps, IHomePageProps } from "./Core";

const core = new Core({
    org: process.env.EZD_ORG,
    token: process.env.EZD_TOKEN,
    rootMapId: process.env.ROOT_MAP_ID,
    ...(process.env.EZD_SCHEME ? {scheme: process.env.EZD_SCHEME} : {}),
    ...(process.env.EZD_HOSTNAME ? {hostname: process.env.EZD_HOSTNAME} : {}), // this way it'll use the default if no scheme/hostname env is set.
    ...(process.env.EZD_ENV ? {env: process.env.EZD_ENV} : {}), // this way it'll use the default if no scheme/hostname env is set.
});

const content_serializer = async () => {
    const content = await content_generator();

    const rootPath = resolve(".","ezd_content");
    try {
        rimraf.sync(rootPath);
    } catch (e) {
        console.error(e);
    }

    mkdirSync(rootPath);

    writeFileSync(resolve(rootPath,"homepage.json"), JSON.stringify(content.homepage, null, 4));
    writeFileSync(resolve(rootPath,"sections.json"), JSON.stringify(content.sections, null, 4));

    for (const [route, pageData] of Object.entries(content.pages as Record<string, IContentPageProps>)) {
        const components = route.split("/");
        const filename = `${components.slice(-1)}.json`;
        const folderPath = join("pages", ...components.slice(0, -1));
        mkdirSync(resolve(rootPath, folderPath), {recursive: true});

        writeFileSync(resolve(rootPath, folderPath, filename), JSON.stringify(pageData, null, 4));
        console.log(`Wrote ${filename} for: ${pageData.title}`);
    }
};

const content_generator = async () => {
    const homepageData = await core.getHomePageData();
    const export_data: {
        homepage: IHomePageProps,
        pages: Record<string, IContentPageProps>,
        sections: Array<{section: ISection, tree: INavTree}>,

    } = {
        homepage: homepageData,
        pages: {},
        sections: [],
    };

    const sections = homepageData.sections;

    const sectionTrees = await Promise.all(sections.map(async section => (await core.client.content.getNavTree(section.href))));

    /*
        name: string;
        route: string;
        id: string;
        children: Array<INavTree>;
    */
    const process_page = async (tree: INavTree, section: string) => {

        try {
            const nodeContent = await core.client.content.getContent(tree.href);
            console.log(`Loaded page: ${tree.title} at ${tree.href}`);
            export_data.pages[tree.href] = nodeContent;
            return Promise.all(tree.children.map(child => process_page(child, section)));
        } catch (e) {
            console.log(`Failed to load page: ${tree.title} at ${tree.href}: ${e}`);
        }
    };

    // await Promise.all(reduced_paths.map(tree => process_page(tree, tree.href, null)));

    for (let id = 0; id < sections.length; id++) {
        const section = sections[id];
        const tree = sectionTrees[id];
        await process_page(tree, section.href);

        export_data.sections.push({section, tree});
        export_data.pages[section.href] = await core.client.content.getContent(section.href);
    }

    return export_data;
};

content_serializer();
