import _ from 'lodash';
import Immutable from 'immutable';
import { ReduceStore } from 'flux/utils';
import { SERVICES_IN_BETA } from 'constants/Services';
import { ActionTypes } from 'constants/Common';
import dispatcher from 'dispatcher';

class SettingsStore extends ReduceStore {
    getInitialState() {
        return new Immutable.Map();
    }

    reduce(state, action) {
        const { data, type } = action;

        switch (type) {
            case ActionTypes.RECEIVE_MIXED_DATA:
                return this._receiveMixedData(data, state);
        }

        return state;
    }

    _receiveMixedData(data, state) {
        const settings = _.pick(data, ['user_settings', 'organization_settings', 'header_settings']);
        const headerServices = _.get(settings, 'header_settings.services');

        if (headerServices) {
            Object.keys(headerServices).forEach(key => {
                if (SERVICES_IN_BETA.indexOf(headerServices[key].slug) !== -1) {
                    headerServices[key].beta = true;
                }
            });
        }

        if (_.isEmpty(settings)) {
            return state;
        }

        return state.merge(settings);
    }

    get(key) {
        return this.getOrganizationSetting(key) || this.getHeaderSetting(key) || this.getUserSetting(key);
    }

    getOrganizationSetting(key) {
        return this.getState().getIn(`organization_settings.${key}`.split('.'));
    }

    getHeaderSetting(key) {
        return this.getState().getIn(`header_settings.${key}`.split('.'));
    }

    getUserSetting(key) {
        return this.getState().getIn(`user_settings.${key}`.split('.'));
    }

    getServices() {
        const services = this.getHeaderSetting('services');

        return services ? services.toJS() : [];
    }

    getUserSettings() {
        const userSettings = this.getState().getIn(['user_settings']);

        return userSettings ? userSettings.toJS() : {};
    }

    getLogoUrl() {
        return this.getHeaderSetting('company_logo');
    }

    isEnabled(name) {
        return Boolean(this.get(name));
    }
}

export default window.ya.connect.SettingsStore = new SettingsStore(dispatcher);
