export class ErrorsService {
    constructor() {
        /**
         * Errors list
         */
        this.errors = {};
        /**
         * Loading state
         */
        this.loading = false;
        /**
         * Errors added event
         */
        this.errorsAdded = new CustomEvent('errorsAdded');
    }
    /**
     * Set loading state
     */
    setLoading(state) {
        this.loading = state;
    }
    /**
     * Get errors by key
     *
     * @param key
     */
    get(key) {
        if (this.errors[key] === undefined) {
            return [];
        }
        if (typeof this.errors[key] === 'string') {
            return [this.errors[key]];
        }
        return this.errors[key] || [];
    }
    /**
     * Remove errors by key
     *
     * @param keys
     */
    remove(keys) {
        if (Array.isArray(keys)) {
            keys.forEach(key => {
                delete this.errors[key];
            });
        }
        else {
            delete this.errors[keys];
        }
    }
    /**
     * Fill errors from HTTP response
     *
     * @param errors
     */
    fill(errors) {
        this.errors = errors || {};
        document.dispatchEvent(this.errorsAdded);
    }
    /**
     * Return all errors from list
     */
    all() {
        return this.errors;
    }
    /**
     * Clear all errors from list
     */
    clear() {
        this.errors = {};
    }
    /**
     * Create service
     *
     * @returns
     */
    static create() {
        const instance = new ErrorsService();
        return Object.assign((errors) => instance.fill(errors), {
            setLoading: (state) => instance.setLoading(state),
            get: (key) => instance.get(key),
            remove: (keys) => instance.remove(keys),
            fill: (errors) => instance.fill(errors),
            all: () => instance.all(),
            clear: () => instance.clear(),
        });
    }
}
export const Errors = ErrorsService.create();
