/**
 * Ciemna szata dla skórki Wektor i wersji mobilnej.
 * Opis: ].
 * Autor: ].
 */

$(function(){
    var GADGET_PREF_KEY = 'gadget-vector-dark-styles';
    var STYLES_GADGET = 'ext.gadget.vector-dark-styles';
    var DEFAULT_OPTIONS = {
        isOn: false
    };

    var THEMES = {
        dark: {
            htmlClass: 'enable-dark-skin',
            toggleButton: null
        },
        light: {
            htmlClass: 'disable-dark-skin',
            toggleButton: null
        }
    };

    var gadgetOptions = DEFAULT_OPTIONS;


    function insertToggles(){
        var portletId;
        if(mw.config.get('skin') !== 'minerva'){
            portletId = 'p-navigation';
        }else{
            portletId = 'pt-preferences';
        }

        THEMES.dark.toggleButton = mw.util.addPortletLink(portletId, 'javascript:void(0)', 'Tryb jasny');
        if ( THEMES.dark.toggleButton ) {
        	THEMES.dark.toggleButton.addEventListener('click', function(){ setTheme(false); });
        }

        THEMES.light.toggleButton = mw.util.addPortletLink(portletId, 'javascript:void(0)', 'Tryb ciemny');
        if ( THEMES.light.toggleButton ) {
        	THEMES.light.toggleButton.addEventListener('click', function(){ setTheme(true); });
        }
    }

    function setTheme(isOn){
        gadgetOptions.isOn = isOn;
        saveThemeOptions();
        applyCurrentOptions();
    }

    function applyCurrentOptions(){
        var themeOff = gadgetOptions.isOn ? THEMES.light : THEMES.dark;
        var themeOn = gadgetOptions.isOn ? THEMES.dark : THEMES.light;

        var htmlClassList = document.documentElement.classList;
        htmlClassList.remove(themeOff.htmlClass);
        htmlClassList.add(themeOn.htmlClass);

        if (themeOff.toggleButton) themeOff.toggleButton.style.display = 'none';
        if (themeOn.toggleButton) themeOn.toggleButton.style.display = '';

        var themeColor = gadgetOptions.isOn ? '#222' : '#eaecf0';
        var metaThemeColor = document.querySelector('meta');
        if(metaThemeColor) metaThemeColor.setAttribute('content', themeColor);

        if (gadgetOptions.isOn){
            // Loads the actual styles. ResourceLoader will not load them for the second time
            mw.loader.load(STYLES_GADGET);
        }
    }

    function saveThemeOptions(){
        var newOptionValue = Number(gadgetOptions.isOn);
        mw.user.options.set(GADGET_PREF_KEY, newOptionValue);
        new mw.Api().saveOption(GADGET_PREF_KEY, newOptionValue);
    }

    function readThemeOptions(){
        gadgetOptions = {
            isOn: mw.user.options.get(GADGET_PREF_KEY) === '1'
        };
    }

    mw.loader.using(, function(){
        readThemeOptions();
        insertToggles();
        applyCurrentOptions();
    });
});