import BaseComponent from "../BaseComponent";
import { fetchData } from "../../Utils/Fetch";

class AppError {
    init() {
        if (!jQuery('.error-ui')[0]) {
            return;
        }
        if (jQuery('.error-ui').data('initializied') !== 'true') {
            new AppErrorHandler(jQuery('.error-ui'));
        }
    }
}

class AppErrorHandler extends BaseComponent {

    constructor(component_base_ui) {
        super(component_base_ui);
        this._form = this._component_base_ui.find('.resendactivation-form');
        this._submitBtn = this._form.find(':submit');
        
        this.handleRouteChange();

        this.handlePopupClickOutside({
            newHash: '',
        });

        this._handleEvents();
    }

    onRouteChange(payload) {
        if (payload?.key === 'error') {
            this._showPopup(payload);
        } else {
            this._closePopup();
        }
    }

    _showPopup(payload) {
        document.title = payload?.data?.page_title ?? '';
        this.checkRecaptcha();
        this.show();
        this.fadeIn();
        this.hideFormErrorOnLoad();
        this.hideFormSuccessOnLoad();
        this.showForm();
        this._component_base_ui.find('.main-error').show();
        this._component_base_ui.find('.back-to-signup').show();
        this._component_base_ui.find('.back-to-login').hide();
    }

    _closePopup() {
        this.hide();
        this.fadeOut();
    }

    _handleEvents() {
        const _this = this;
        this._form.on('submit', function(event) {
            event.preventDefault();
            _this._handleSubmit();
            return;
        })
    }

    async _handleSubmit() {

        let payload = {
            email: this._component_base_ui.find('input[name="email"]').val(),
        }

        this._submitBtn.attr('disabled', true);
        this.hideFormErrorOnLoad();

        const result = await fetchData('user-resend-activation', 'POST', payload);
        if (result?.status === 200) {
            this.showFormSuccess();
            this.hideForm();
            this._component_base_ui.find('.main-error').hide();
            this._component_base_ui.find('.back-to-signup').hide();
            this._component_base_ui.find('.back-to-login').show();
        } else {
            this._component_base_ui.find('.form-error').html(result?.message);
            this.showFormError();
        }
        this._submitBtn.attr('disabled', false);
    }
}

export default AppError;