document.addEventListener(`DOMContentLoaded`, e => {
    handleImageGeneratorForm();
})

const randomPrompts = [
    `A charming skyscraper, nightfall`,
    `An intense action figure of a disruptive shrew in an empty marsh, in the golden hour.`,
]

var generatedImage = ``;
var generatedImageDownloadBase64 = ``;
var nextSubmitAllowedTime = 0;

function generateRandomPrompt() {

    const sentences = [
        `_TYPE_ of _SUBJECT_ _ACTION_ _ENVIRONMENT_, _EXTRAS_`,
    ]

    const types = [
        `An illustration`,
        `A digital illustration`,
        `A realistic illustration`,
        `A artsy illustration`,
        `A photograph`,
        `A DSLR Picture`,
        `A DSLR Photograph`,
        `A digital painting`,
        `A digital drawing`,
        `A digital sketch`,
        `A film photograph`,
    ];

    const subjects = [
        `A penguin`,
        `A dog`,
        `A man`,
        `A woman`,
        `A cat`,
        `A kitten`,
        `A dog`,
        `A fish`,
        `A squirrel`,
        `A chipmunk`,
        `A capybara`,
    ];

    const action = [
        `wearing a tuxedo`,
        `wearing a top hat`,
        `dressed with in a long skirt`,
        `posing for a picture`,
        `running`,
        `sleeping on the left side`,
        `looking at the viewer`,
        `posing at the viewer`,
        `posing at the viewer`,
    ]

    const environments = [
        `in a green forest`,
        `in a white room`,
        `with an interesting background`,
        `with a studio background`,
        `with a realistic background`,
        `with a fantasy background`
    ];

    const extras = [
        `masterpiece, masterwork, artsy, creative, imagination, (realistic:1.1)`,
        `masterpiece, masterwork, artsy, creative, imagination`,
        `(realistic:1.1), DSLR, picture, photograph, polaroid`,
        `film photography, kodak gold, kodak, 35mm film, film picture`,
    ]

    return randomItem(sentences)
        .replace(/_TYPE_/g,         randomItem(types))
        .replace(/_SUBJECT_/g,      randomItem(subjects))
        .replace(/_ACTION_/g,       randomItem(action))
        .replace(/_ENVIRONMENT_/g,  randomItem(environments))
        .replace(/_EXTRAS_/g,       randomItem(extras))

}

function randomItem(items) { return items[Math.floor(Math.random()*items.length)]; }

async function handleImageGeneratorForm() {
    /**
     * @type {HTMLFormElement}
     */
    const imageGeneratorForm = document.getElementById(`image-generator`);

    if ( !!imageGeneratorForm ) {

        // Randomize the prompt as a starting point
        document.getElementById(`image_description`).value = `vaporwave, (vaporwave style:1.1), synthwave, 80's, aesthetic,`;

        imageGeneratorForm.querySelector(`#random-prompt-button`).addEventListener( `click`, e => {
            e.preventDefault();

            document.getElementById(`image_description`).value = generateRandomPrompt();

        })

        imageGeneratorForm.querySelector(`#download-image-button`).addEventListener( `click`, e => {
            e.preventDefault();

            if ( !!generatedImageDownloadBase64 ) {
                window.location.href = 'data:application/octet-stream;base64,' + generatedImageDownloadBase64;
            }

        })

        imageGeneratorForm.querySelector(`#submit-image-button`).addEventListener( `click`, async (e) => {

            // Cancel the default post, we wills end the data to an API endpoint
            e.preventDefault();

            if ( nextSubmitAllowedTime > new Date().getTime() ) {
                const s = ((nextSubmitAllowedTime - new Date().getTime()) / 1000).toFixed(1);
                alert(`Please wait ${s} more seconds before trying to submit`);
                return;
            }

            if ( generatedImage == null || !!!generatedImage ) {
                alert(`This image has already been submited`);
                return;
            }

            // Disable the form
            imageGeneratorForm.classList.add(`loading`);
            imageGeneratorForm.querySelector(`button.btn-95`).setAttribute(`disabled`, true);

            const fData = new FormData();
            fData.set(`image_data`, generatedImage);

            const response = await fetch(`/api/image/submit`, {
                body:   fData,
                method: `POST`,
            })
            .catch( err => {
                alert("Something went wrong with postiong your image, please try again later.");
                console.error(err);
            })

            // Enable the form
            imageGeneratorForm.classList.remove(`loading`);
            imageGeneratorForm.querySelector(`button.btn-95`).removeAttribute(`disabled`);

            generatedImage = null;
            document.getElementById(`submit-image-button`).setAttribute(`disabled`, 123);
            alert(`Your image has been submitted! Thanks for posting`);

            nextSubmitAllowedTime = new Date().getTime() + (1000 * 15);
        })

        imageGeneratorForm.addEventListener(`submit`, async (e) => {
            // Cancel the default post, we wills end the data to an API endpoint
            e.preventDefault();

            // Disable the form
            imageGeneratorForm.classList.add(`loading`);
            imageGeneratorForm.querySelector(`button.btn-95`).setAttribute(`disabled`, true);

            const response = await fetch(`/api/image/generate`, {
                body:   new FormData(imageGeneratorForm),
                method: `POST`,
            })
            .catch( err => {
                alert("Something went wrong with generating the image, please try again later.");
                console.error(err);
            })

            // Enable the form
            imageGeneratorForm.classList.remove(`loading`);
            imageGeneratorForm.querySelector(`button.btn-95`).removeAttribute(`disabled`);

            /**
             * @type {HTMLDivElement}
             */
            const imageResultElement = imageGeneratorForm.querySelector(`#image-generation-result`);
            const imgPlaceholder = imageResultElement.querySelector(`#tmp-img-placeholder`);
            if ( !!imgPlaceholder ) {
                imgPlaceholder.remove();
            }

            const r = await response.json();

            imageResultElement.style.setProperty(`background-image`, `url('data:image/jpeg;charset=utf-8;base64,${r.images[0]}')`);

            document.getElementById(`submit-image-button`).removeAttribute(`disabled`);

            generatedImage = r.images[0];
            generatedImageDownloadBase64 = r.images[0];

        })
    }
}