import { deepCopy } from '../_utils/object';
import { validate } from './form-helper';
var FormInstance = (function () {
    function FormInstance(initValues) {
        if (initValues === void 0) { initValues = {}; }
        this.rules = {};
        this.errors = {};
        this.listeners = [];
        this.initValues = initValues;
        this.values = deepCopy(initValues);
    }
    FormInstance.prototype.getFieldValues = function () {
        return this.values;
    };
    FormInstance.prototype.getFieldValue = function (name) {
        return this.values[name];
    };
    FormInstance.prototype.setFieldValue = function (name, val) {
        this.values[name] = val;
        this.notify(name);
    };
    FormInstance.prototype.setFieldValues = function (values) {
        var _this = this;
        if (values === void 0) { values = {}; }
        Object.keys(values).forEach(function (name) { return _this.setFieldValue(name, values[name]); });
    };
    FormInstance.prototype.getFiledErrors = function () {
        return this.errors;
    };
    FormInstance.prototype.getFieldError = function (name) {
        return this.errors[name] && this.errors[name].length > 0 ? this.errors[name][0] : undefined;
    };
    FormInstance.prototype.setFieldError = function (name, errors) {
        this.errors[name] = errors;
    };
    FormInstance.prototype.setFiledRules = function (name, rules) {
        this.rules[name] = rules;
    };
    FormInstance.prototype.resetFields = function () {
        this.errors = {};
        this.values = deepCopy(this.initValues);
        this.notify('*');
    };
    FormInstance.prototype.validateField = function (name) {
        var rules = this.rules[name];
        var value = this.values[name];
        if (rules) {
            var errMessages_1 = [];
            rules.forEach(function (rule) {
                var res = validate(value, rule);
                if (res !== undefined) {
                    errMessages_1.push(res);
                }
            });
            this.setFieldError(name, errMessages_1);
            this.notify(name);
        }
    };
    FormInstance.prototype.validateFields = function () {
        var _this = this;
        Object.keys(this.rules).forEach(function (name) { return _this.validateField(name); });
    };
    FormInstance.prototype.subscribe = function (listener) {
        var _this = this;
        this.listeners.push(listener);
        return function () {
            var idx = _this.listeners.indexOf(listener);
            idx > -1 && _this.listeners.splice(idx, 1);
        };
    };
    FormInstance.prototype.notify = function (name) {
        this.listeners.forEach(function (listener) { return listener(name); });
    };
    return FormInstance;
}());
export default FormInstance;
//# sourceMappingURL=form-instance.js.map