import Immutable from 'immutable';
import notify, { cancelRequestErrorNotification } from 'services/notify';

const FormMixin = {

    _validate(data) {
        let errors;

        if (this._filter) {
            data = this._filter(data);
        }

        if (this._validator) {
            errors = this._validator.getErrors(data);
        }

        if (errors && !errors.isEmpty()) {
            this.setState({ errors });

            return false;
        }

        const initialState = this.getInitialState ? this.getInitialState() : null;

        if (initialState && initialState.errors) {
            this.setState({ errors: initialState.errors });
        }

        return true;
    },

    _resolve(data) {
        const { onSubmit } = this.props;

        if (onSubmit) {
            onSubmit(data);
        }
    },

    _receiveResponse(response, options = {}) {
        if (response && response.errors) {
            this.setState(response);
        } else {
            notify(options.success, 'success');
            this._resolve(response);
        }

        return response;
    },

    _receiveException(error, options = {}) {
        cancelRequestErrorNotification(error);
        this._setError(options.failure);
    },

    _use(validator, filter) {
        this._validator = validator;
        this._filter = filter;

        return this;
    },

    _submit(request, options) {
        return request
            .then(response => this._receiveResponse(response, options))
            .catch(error => this._receiveException(error, options));
    },

    _setError(error) {
        this.setState({
            errors: error && Immutable.fromJS({ _common: error }),
        });
    },

    _setErrors(errors) {
        this.setState({
            errors: errors && Immutable.fromJS(errors),
        });
    },

};

export default FormMixin;
