import { GalleryManager } from "./SubmissionsClass/GalleryManager.js";

/**
 * If there is some server side errors.
 * We may need reload some things.
 * @type {boolean}
 */
const SERVER_SIDE_ERRORS = document.querySelector('meta[name="submission-has-errors"]')?.content === '1';

/**
 * Object map of errors messages
 * @type {Object<string,string>}
 */
const ERROR_TABLE = {
    noDescription: "Please provide a description.",
    noGalleryImages: "Please select at least a gallery image.",
    isSubmitting: "The entry is already during submission."
}

window.GalleryManager = GalleryManager;

/**
 * Verify if an EasyMDE field is filled.
 *
 * @param {string} fieldName
 * @returns {boolean}
 */
function verifyMDE( fieldName ){
    const textarea = document.querySelector('#field_' + fieldName);
    if( textarea && textarea.value.trim().length > 0 ) {
        return true;
    }

    const field = window['mde_' + fieldName] || null;
    return field && typeof field.value === 'function' && field.value().trim().length > 0;
}

window.SubmissionVerifications = {

    /**
     * Verify if the description field has at least one character.
     * @returns {boolean}
     */
    step1_VerifyDescription: function(){
        return verifyMDE('description');
    },

    /**
     * Verify if at least one image is uploaded in the gallery.
     * @param element this.$el
     * @return {boolean}
     */
    step2_verifyGallery: function( element){
        let GalleryData = element.querySelector('[x-data="GalleryManager()"]');
        GalleryData = GalleryData ? Alpine.$data(GalleryData) : null;

        if( ! GalleryData ){
            return false;
        }

        return GalleryData.number > 0 && GalleryData.allUploaded;
    }

}

/**
 * Handle entire submission process.
 */
window.NewsSubmission = function(){
    return {

        /**
         * If the script is during a try of submission process.
         * @type {boolean}
         */
        duringSubmissionProcess: false,

        /**
         * Error checked.
         * @type {string|null}
         */
        errorKey: null,

        /**
         * Return error message.
         * @return {string}
         */
        get errorMessage(){
          return ERROR_TABLE[this.errorKey] ?? "Unknown error";
        },

        init(){
        },

        /**
         * Do each form verifications.
         * Update also this.errorKey.
         *
         * @returns {boolean}
         */
        verifyForm(){

            console.log( "Step 1" );
            if( !SubmissionVerifications.step1_VerifyDescription() ){
                this.errorKey = "noDescription";
                return false;
            }

            console.log( "Step 2" );
            if( !SubmissionVerifications.step2_verifyGallery( this.$el )){
                this.errorKey = "noGalleryImages";
                return false;
            }

            return true;

        },

        /**
         * Scroll to the specific error field.
         */
        scrollToError(){
            const refMap = {
                noDescription: 'descriptionField',
                noGalleryImages: 'gallery-field',
                isSubmitting: 'submitButton'
            };

            const target = this.$refs[refMap[this.errorKey]]
                || this.$el.querySelector('.upload-list')
                || this.$el.querySelector('.form-upload');

            if (target) {
                target.scrollIntoView({behavior: 'smooth', block: 'center'});
                return;
            }
        },

        /**
         * If you want to submit the form.
         * @param {Event} e
         */
        submitForm( e ){

            if( this.duringSubmissionProcess )
                return; // Don't submit two times.

            this.errorKey = null; // Reset.
            this.duringSubmissionProcess = true;

            const STATE = document.querySelector('select[name="submit-state"]')?.value;
            if( STATE === 'draft' ){
                e.target.submit();
                return;
            }

            if( !this.verifyForm() ){

                this.scrollToError();

                this.duringSubmissionProcess = false;
                return;
            }

            e.target.submit();
        }

    }
}
