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

class SessionStore 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);
            case ActionTypes.RECEIVE_SESSION:
                return state.set(data.id, data);
            case ActionTypes.DISCARD_SESSION:
                return state.remove(data.id);
        }

        return state;
    }

    /**
     * Возвращает организацию по id
     * @method  get
     * @param   {String} id
     * @returns {Object}
     */
    get(id) {
        return this._state.get(id);
    }

    getAll() {
        return this._state.toArray();
    }

    getAllMap() {
        return this._state.toObject();
    }

    /**
     * Возвращает email пользователя по id
     * @method  getUserEmail
     * @param   {String} id
     * @returns {String}
     */
    getUserEmail(id) {
        const login = this.get(id) && this.get(id).login;

        if (login) {
            return login + (login.indexOf('@') === -1 ? '@yandex.ru' : '');
        }
    }

    getList() {
        return (this._order || []).map(id => this.get(id));
    }

    _receiveRawData(state, data) {
        if (data.sessions) {
            this._order = (_.find(data.lists, { type: 'sessions' }) || {}).order;

            return new Immutable.Map(data.sessions)
                .map(item => Session.create(item));
        }

        return state;
    }
}

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