import _ from 'lodash';
import Immutable from 'immutable';
import { ReduceStore } from 'flux/utils';
import { ActionTypes } from 'constants/Common';
import dispatcher from 'dispatcher';
import DomainStore from 'stores/Domains';

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

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

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

        return state;
    }

    _receiveRawData(state, data) {
        if (data.resources) {
            _.entries(data.resources).forEach(([serviceSlug, resourceData]) => {
                if (!resourceData) {
                    return;
                }

                _.entries(resourceData).forEach(([key, item]) => {
                    state = state.setIn([serviceSlug, key], Immutable.fromJS(item));
                });
            });
        }

        ['relations', 'roles', 'requests'].forEach(field => {
            if (data[field]) {
                const { service, resourceId, items } = data[field];

                state = state.setIn([service, 'list', resourceId, field], Immutable.fromJS(items));
            }
        });

        return state;
    }

    has(serviceSlug, resourceId) {
        return Boolean(this._state.getIn([serviceSlug, 'list', resourceId]));
    }

    getList(serviceSlug) {
        const resources = this._state.getIn([serviceSlug, 'list']);

        return resources ? resources.toArray().map(item => item.toJS()) : [];
    }

    getCount(serviceSlug) {
        if (serviceSlug === 'webmaster') {
            return DomainStore.getCount();
        }

        return this._state.getIn([serviceSlug, 'count']);
    }

    getResponsibleId(serviceSlug) {
        return this._state.getIn([serviceSlug, 'responsible']);
    }

    getResource(serviceSlug, id) {
        const resource = this._state.getIn([serviceSlug, 'list', id]);

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

    getRoles(serviceSlug, resourceId) {
        const roles = this._state.getIn([serviceSlug, 'list', resourceId, 'roles']);

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

    getRequestCount(serviceSlug, resourceId) {
        const requests = this._state.getIn([serviceSlug, 'list', resourceId, 'requests']);

        return requests ? requests.size : 0;
    }
}

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