import _ from 'lodash';
import Immutable from 'immutable';
import { ReduceStore } from 'flux/utils';
import { ActionTypes } from 'constants/Common';
import dispatcher from 'dispatcher';
import { i18n } from 'lib/i18n';
import ConfigStore from 'stores/Config';

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

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

        switch (type) {
            case ActionTypes.RECEIVE_MIXED_DATA:
                if (data.services) {
                    return state.merge(data.services);
                }
        }

        return state;
    }

    get(key) {
        return this.getState().getIn(key.split('.'));
    }

    getService(key) {
        const service = this.get(key);

        if (!service) {
            return {
                url: ConfigStore.getRelatedServiceUrl(key),
                name: i18n(`dashboard.card.${key}.title`),
            };
        }

        return _.assign(service.toJS(), { key });
    }

    getServices() {
        return this.getState().toJS();
    }

    getUrl(key) {
        return this.getState().getIn([key, 'url']);
    }

    getName(key) {
        return this.getState().getIn([key, 'name']);
    }

    getIcon(key) {
        return this.getState().getIn([key, 'icon']);
    }
}

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