
import BaseComponent from '../BaseComponent';
import { fetchData } from '../../Utils/Fetch';
import AppData from '../../Common/AppData';

class UserPopupMenu {

    init() {
        if (!jQuery('.user-profile-popup-menu')[0]) {
            return;

        }
        if (jQuery('.user-profile-popup-menu').data('initializied') !== 'true') {
            new UserPopupMenuHandler(jQuery('.user-profile-popup-menu'))
        }
    }
}

class UserPopupMenuHandler extends BaseComponent {

    constructor(component_base_ui) {
        super(component_base_ui);
        this._handleEvents();
    }

    _handleEvents() {
        const _this = this;
        jQuery('.user-menu-icon').on('click', function(event) {
            event.preventDefault();
            if (_this._component_base_ui.hasClass('hidden')) {
                _this._component_base_ui.removeClass('hidden');
            } else {
                _this._component_base_ui.addClass('hidden');
            }
        })

        jQuery(document).click(function(event) {
            if (!jQuery(event.target).closest(".user-menu-icon, .user-profile-popup-menu").length) {
                if (!_this._component_base_ui.hasClass('hidden')) {
                    _this._component_base_ui.addClass('hidden');
                }
            }
        });

        this._component_base_ui.find('.logout-btn').on('click', function(event) {
            event.preventDefault();
            jQuery(this).attr('disabled', true);
            _this._logout();
        })

        this._component_base_ui.find('li a').each(function(event) {
            jQuery(this).on('click', function(event) {
                if (!_this._component_base_ui.hasClass('hidden')) {
                    _this._component_base_ui.addClass('hidden');
                }
            })
        })
    }

    async _logout() {
        const result = await fetchData('logout', 'GET');
        if (result?.status === 200) {
            this._component_base_ui.find('.re-send-info').removeClass('hidden');

            const { login } = AppData.getInstance().get('routes');
            const app_url = AppData.getInstance().get('app_url');
            const url = `${app_url}#${login?.hash}`;
            window.location.replace(url);
        } else {
            alert(`${result?.message}`);
        }
    }
}

export default UserPopupMenu;