import Cookies from 'js-cookie';

export default function settings() {
    return {

        /**
         * @type {boolean}
         */
        start: false,

        /**
         * Two keys, default and alternate.
         * @type {Object}
         */
        xfUrls: {},

        /**
         * @type {string}
         */
        currentTheme: 'default',

        /**
         * @type {list|null}
         */
        currentActivityFilters: null,

        /**
         *
         * @param {string} newTheme default|alternate
         */
        themeChanged( newTheme ){
            if( newTheme !== "default" && newTheme !== "alternate" )
                return;

            if( newTheme === this.currentTheme )
                return;

            this.currentTheme = newTheme;
            document.documentElement.classList.toggle('light-mode', this.currentTheme === 'alternate');

            // Cookies.set('theme', this.currentTheme, { expires: 365, path: '/', domain: window.getConfig('session-domain') } );
            this.syncXF();
        },

        /**
         *
         * @return {Promise<void>}
         */
        async syncXF(){
            await fetch(this.xfUrls[this.currentTheme ?? 'default'], { method: "GET", credentials: "include", mode: "no-cors" });
        },

        /**
         *
         */
        toggleTheme(){
            this.themeChanged(this.currentTheme === 'default' ? 'alternate' : 'default');
        },

        open(){ this.start = !this.start; },
        close(){ this.start = false; },

        async toggleActivityFilter( type ){

            if( this.currentActivityFilters === null )
                return;

            const i = this.currentActivityFilters.indexOf( type );
            if( i !== -1 && this.currentActivityFilters.length === 1)
                return;

            if( i === -1 )
                this.currentActivityFilters.push( type );
            else
                this.currentActivityFilters.splice( i, 1 );

            Cookies.set( 'activity_filters', JSON.stringify(this.currentActivityFilters), { expires: 365, path: '/', domain: window.getConfig('session-domain') } );
            await this.syncTimeline();
        },

        async syncTimeline(){

            const tl = document.getElementById('activity-timeline');
            if( !tl )
                return;

            tl.style.opacity = 0.5;

            const params = this.currentActivityFilters.join(',');
            const response = await fetch(`/api/dynamic/activity/feed?filters=${params}`);
            const data = await response.json();

            if( !data.html )
                return;

            tl.innerHTML = data.html;
            tl.style.opacity = 1;

            refreshIcons(tl);

        }

    }
}
