import _ from 'lodash';
import { ActionTypes } from 'constants/Common';
import dispatcher from 'dispatcher';
import getErrors from 'lib/getErrors';
import settingsApi from 'api/settings';
import SettingsStore from 'stores/Settings';

const settingActions = {
    updateSettings,
    fetchSettings,
};

_.set(window.ya.connect, 'action.settings', settingActions);

export default settingActions;

/**
 * Обновление настроек
 * @method updateSettings
 * @param  {Object}    data
 * @returns {Promise}
 */
function updateSettings(data) {
    const settings = _.extend({}, SettingsStore.getUserSettings(), data);

    return settingsApi.update(settings).then(response => {
        const errors = getErrors(response);

        if (!errors.isEmpty()) {
            return { errors };
        }

        dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);

        return response;
    });
}

function fetchSettings() {
    return settingsApi.read().then(response => {
        const errors = getErrors(response);

        if (!errors.isEmpty()) {
            return { errors };
        }

        dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);
    });
}
