import {ImageOptimizer} from "./ImageOptimizer";

/**
 * Recognize Image Upload - base component
 */
export class RecognizeImageUpload {
    __url = '';
    __imageInputId = '';

    __appendRequestProperties = (data) => {return {}};
    __onUpload = (data) => {};// callback
    __onError = (jqXHR, textStatus, errorThrown) => {};
    __onFinish = (data, textStatus, errorThrown) => {};

    /**
     * @param url
     * @param settings
     */
    constructor(url, settings = {}) {
        this.__url = url;
        this.__imageInputId = settings.imageInputId || '';

        if (settings.onUpload && typeof settings.onUpload === 'function') {
            this.__onUpload = settings.onUpload;
        }

        if (settings.onError && typeof settings.onError === 'function') {
            this.__onError = settings.onError;
        }

        if (settings.onFinish && typeof settings.onFinish === 'function') {
            this.__onFinish = settings.onFinish;
        }

        if (settings.appendRequestProperties && typeof settings.appendRequestProperties === 'function') {
            this.__appendRequestProperties = settings.appendRequestProperties;
        }
    }

    /**
     * Ajax with loader-spinner
     * Require json response from endpoint
     * @returns {Promise<void>}
     */
    async sendAjaxWithLoader(imageFile = null) {
        let imageInputIdOrFile = imageFile || this.__imageInputId;
        let onUpload = this.__onUpload;
        let onFinish = this.__onFinish;
        let onError = this.__onError;

        const isFile = imageInputIdOrFile => 'File' in window && imageInputIdOrFile instanceof File;
        const isBlob = imageInputIdOrFile => 'Blob' in window && imageInputIdOrFile instanceof Blob;
        const isInputFile = isFile || isBlob;

        let file = null;
        if (isInputFile) {
            file = imageInputIdOrFile;
        } else {
            file = document.getElementById(imageInputIdOrFile).files[0];
        }

        // skip on empty file
        if (!file) {
            return ;
        }

        // convert to base64
        let image =  await (new ImageOptimizer).convertImage(file);// Sync
        let imageName = file.name;

        let formData = new FormData();
        formData.append('image', image);
        formData.append('imageName', imageName);

        const CSRF = this.__getCSRF();
        if (CSRF) {
            formData.append(CSRF.param, CSRF.token);// should be init on the php layout
        }

        // append additional request properties
        let additionalProperties = this.__appendRequestProperties();
        Object.keys(additionalProperties).forEach((key) => {
            formData.append(key, additionalProperties[key]);
        })
        formData.append('locationHref', window.location.href)

        // show loader
        $('.photo-btn').css('display', 'none');
        $('.photo-btn-loading').css('display', 'block');

        // add loader + lock icon
        return $.ajax({
            url: this.__url,
            dataType: 'json',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
        })
            .done((data) => onUpload(data))
            .fail((jqXHR, textStatus, errorThrown) => {
                console.error(textStatus, errorThrown);
                alert('Error recognition ajax');
                onError(jqXHR, textStatus, errorThrown);
            })
            .always((data, textStatus, errorThrown) => {
                // disable loader
                $('.photo-btn').css('display', 'block');
                $('.photo-btn-loading').css('display', 'none');

                if (!isInputFile) {
                    document.getElementById(imageInputIdOrFile).value = '';
                }

                onFinish(data, textStatus, errorThrown);
            });
    }

    /**
     * CSRF
     * @returns {null|{param: string, token: string}}
     * @private
     */
    __getCSRF() {
        return {
            param: $('meta[name="csrf-param"]').attr("content"),
            token: $('meta[name="csrf-token"]').attr("content"),
        };
    }
}