import { athenaConfigOptions } from '../../global/athena-config.js';
import { hideAutocompleteBox } from '../../autocomplete/ajax/ajax.js';

/**
 * Elements Required
 *
 * @returns {{backgroundOverlay: Element, athenaBody: HTMLBodyElement, containerAfterDrop: Element, containerBeforeDrop: Element, previewImage: Element, containerElement: Element}}
 */
function visualSimilarityElements() {
    return {
        containerBeforeDrop: document.querySelector('.visual-similarity__drop-container'),
        containerAfterDrop: document.querySelector('.visual-similarity__dropped-image-container'),
        containerElement: document.querySelector('#visual_similarity_search'),
        backgroundOverlay: document.querySelector('.overlay-background'),
        previewImage: document.querySelector('#preview-image'),
        athenaBody: document.getElementsByTagName('body')[0],
        infoContainer: document.querySelector('.visual-similarity-info__container'),
        visualSimilarityTitle: document.querySelector('.visual-similarity-p__container .visual-similarity__p'),
    }
}

/**
 * Handle Edit button click function
 *
 * @param imageSrc
 */
function handleEditButtonClick(imageSrc) {
    athenaConfigOptions.cropper?.destroy();
    hideAutocompleteBox();

    Promise.all([
        import('../../global/cropper/cropper.js')
    ])
        .then(([CropperModule]) => {
            athenaConfigOptions.cropperInstance = CropperModule.default;

            const vssElements = visualSimilarityElements();
            vssElements.containerElement?.classList.toggle('athena-helper-show');
            vssElements.backgroundOverlay?.classList.add('background-overlay');
            vssElements.previewImage.src = imageSrc;
            vssElements.containerBeforeDrop?.classList.add('athena-helper-hide');
            vssElements.containerAfterDrop?.classList.add('athena-helper-show');
            vssElements.infoContainer?.classList.add('athena-helper-hide');
            if(vssElements.visualSimilarityTitle){
                vssElements.visualSimilarityTitle.innerHTML = 'Crop the image'
            }

            document.body.classList.add('athena-disable-scroll');
            document.body.classList.add('edit-croper-open');

            athenaConfigOptions.cropper = new window.Cropper(vssElements.previewImage, {
                viewMode: 2,
                aspectRatio: 'Free',
                minContainerHeight: 300,
                minCanvasHeight: 300,
                autoCropArea: 0.99
            });

            vssElements.athenaBody.classList?.remove('athena-search-filter-open');
        });
}

/**
 * Handle Camera Click Event Function
 *
 * @param imageSrc
 */
function handleEditButton(imageSrc) {
    const editButton = document.querySelector('.edit-button__visual-similarity-search');
    editButton?.addEventListener('click', () => handleEditButtonClick(imageSrc));
}

export default handleEditButton;
