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

class LanguageSwitcher {

    init() {
        if (!jQuery('.lang-choose-menu')[0]) {
            return;

        }
        if (jQuery('.lang-choose-menu').data('initializied') !== 'true') {
            new LanguageSwitcherHandler(jQuery('.lang-choose-menu'))
        }
    }
}

class LanguageSwitcherHandler extends BaseComponent {
    constructor(component_base_ui) {
        super(component_base_ui);
        this._handleEvents();
    }

    _handleEvents() {
        const _this = this;
        jQuery('.lang-switcher-ui').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(".lang-switcher-ui, .lang-choose-menu").length) {
                if (!_this._component_base_ui.hasClass('hidden')) {
                    _this._component_base_ui.addClass('hidden');
                }
            }
        });

        jQuery('.lang-choose-menu').find('.lang-switcher-btn').on('click', function(event) {
            event.preventDefault();
            const lang = jQuery(this).data('lang');
            console.log('Language selected:', lang);
            if (lang) {
                _this._changeLanguage(lang);
            }
        })
    }

    async _changeLanguage(lang) {
        const result = await fetchData('set-language', 'POST', { lang });
        if (result?.status === 200) {
            window.location.reload();
        }
    }
}

export default LanguageSwitcher;