/**
 * Хранилище данных о доступных кодах для приглашения пользователя
 */

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

import Invite from 'records/Invite';

class InviteStore extends ReduceStore {
    getInitialState() {
        return Immutable.fromJS({
            code: {}, department: {},
        });
    }

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

        switch (type) {
            case ActionTypes.RECEIVE_MIXED_DATA:
                return this._receiveMixedData(state, data);
            case ActionTypes.RECEIVE_INVITE_LINK:
                return state.setIn(['department', String(data.departmentId)], Immutable.Map(data.invites));
            case ActionTypes.DISCARD_INVITE_LINK:
                return state.removeIn(['department', String(data.departmentId)]);
        }

        return state;
    }

    _receiveMixedData(state, data) {
        let nextState = state;

        if (data.invites) {
            const nextIndex = new Immutable.Map(data.invites)
                .map(item => Invite.create(item));

            nextState = nextState.mergeIn(['code'], nextIndex);
        }

        return nextState;
    }

    get(id) {
        return this._state.getIn(['code', id]);
    }

    getCodeByDepartmentId(deptId) {
        return this._state.getIn(['department', deptId, 'code']);
    }
}

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