import { merge } from "lume/core/utils/object.ts";
import mtnt from "./pluginData/mutant.json" with { type: "json" }
import Site from "lume/core/site.ts";

export interface Options {
    /** Extensions processed by this plugin to extract the utility classes */
    extensions?: string[];
}
export const defaults: Options = {
    extensions: [".md", ".mdx", ".html"],
};

function replaceSlashes(text: string) {
    return text.replace(/\//g, '+');
}

export default function (userOptions?: Options) {
    const options = merge(defaults, userOptions);
    const alreadyProcessed: string[] = [];
    return (site: Site) => {
        site.process(options.extensions, (pages) => {
            pages.forEach((page: any) => {
                const regex = /(?<= ):(.*?):(?= )/g;
                let m: RegExpExecArray | null;
                while ((m = regex.exec(page.content as unknown as string)) !== null) {
                    const text = m[0].trim();
                    const textBetweenColons = m[1].trim();
                    // deno-lint-ignore ban-ts-comment
                    // @ts-ignore 
                    // console.log(textBetweenColons, mtnt, mtnt.some(item => item.short === textBetweenColons))
                    // console.log(mtnt.some(item => item.short === textBetweenColons), mtnt.find(item => item.short === textBetweenColons))
                    if (mtnt.some(item => item.short === textBetweenColons)) {
                        const emoji = mtnt.find(item => item.short === textBetweenColons)
                        const emojiPath = replaceSlashes(emoji.src);
                        if (page.data.url === '/') {
                            // console.log((page.content as unknown as string).replace(new RegExp(text, 'g'), text))
                        }
                        page.content = (page.content as unknown as string).replace(new RegExp(text, 'g'),
                            `<img alt="${emoji.desc}" class="markdown-emoji" src="/files/emojis/${emojiPath}" />`);

                        if (!alreadyProcessed.includes(textBetweenColons)) {
                            alreadyProcessed.push(textBetweenColons);
                            console.log(alreadyProcessed)
                            site.getOrCreatePage(`/files/emojis/${emojiPath}`)
                        }
                    }
                }
            });
        });
    };
}
