import _ from 'lodash';
import Immutable from 'immutable';
import { ReduceStore } from 'flux/utils';
import { ActionTypes } from 'constants/Common';
import dispatcher from 'dispatcher';
import Organization from 'records/Organization';
import AuthStore from 'stores/Auth';

class OrganizationStore 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_ORGANIZATION:
                return this._updateOrgData(state, data);
            case ActionTypes.DISCARD_ORGANIZATION:
                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();
    }

    /**
     * Возвращает количество организаций
     * @returns {Number}
     */
    getSize() {
        return this._state.size;
    }

    /**
     * Возвращает основной домен организации
     * @param   {String}  orgId
     * @returns {String}
     */
    getMasterDomain(orgId) {
        if (!orgId) {
            orgId = AuthStore.getOrganizationId();
        }

        return this._state.getIn([orgId, 'domains', 'master']);
    }

    /**
     * Возвращает имя организации
     * @param   {String}  id
     * @returns {String}
     */
    getOrgName(id) {
        return this._state.getIn([id, 'name']);
    }

    _receiveRawData(state, data) {
        if (data.organizations) {
            const nextState = new Immutable.Map(data.organizations)
                .map(item => Organization.create(item));

            return state.merge(nextState);
        }

        return state;
    }

    _updateOrgData(state, data) {
        if (data) {
            const prevData = state.get(data.id).toJS();
            const nextState = Organization.create(_.extend(prevData, data));

            return state.set(data.id, nextState);
        }

        return state;
    }

    hasOwnedDomains(orgId) {
        if (!orgId) {
            orgId = AuthStore.getOrganizationId();
        }

        return this._state.getIn([orgId, 'has_owned_domains']);
    }
}

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