import ErrorModel from "./ErrorModel.js";
import ErrorModelCollectionEvent, { ErrorModelCollectionEventType } from "./ErrorModelCollectionEvent.js";
export default class ErrorModelCollection {
    constructor(errors = []) {
        this.m_collection = new Jade.Collection();
        this.m_eventBus = new Jade.EventBus({
            label: "error-model-collection"
        });
        errors?.forEach(item => {
            this.collection.add(new ErrorModel(item));
        });
    }
    get collection() {
        return this.m_collection;
    }
    get eventBus() {
        return this.m_eventBus;
    }
    get eventName() {
        return "error-model-collection:event";
    }
    add(item) {
        let result = this.collection.add(item);
        this.publish(item, ErrorModelCollectionEventType.add);
        return result;
    }
    clear() {
        this.collection.clear();
        this.publish(null, ErrorModelCollectionEventType.clear);
    }
    getByGroup(groupIndex) {
        let result = [];
        this.collection.each(item => {
            item.groupIndex === groupIndex ?
                result.push(item) : null;
        });
        return result;
    }
    getByFeature(groupIndex, featureIndex) {
        let result = [];
        this.getByGroup(groupIndex).forEach(item => {
            item.featureIndex === featureIndex ?
                result.push(item) : null;
        });
        return result;
    }
    load(items = []) {
        items = items || [];
        this.clear();
        items.forEach(error => {
            this.collection.add(new ErrorModel(error));
        });
        this.publish(null, ErrorModelCollectionEventType.load);
    }
    remove(item) {
        let result = this.collection.remove(item);
        this.publish(item, ErrorModelCollectionEventType.remove);
        return result;
    }
    subscribe(callback, type = null) {
        let result = type != null ?
            this.eventBus.subscribe(`${this.eventName}:${type}`, callback) :
            this.eventBus.subscribe(this.eventName, callback);
        return result;
    }
    toJSON() {
        return this.collection.transform((item) => {
            return item.toJSON();
        });
    }
    publish(item, eventType = null) {
        let target = new ErrorModelCollectionEvent({
            error: item,
            errors: this,
            eventType: ErrorModelCollectionEventType.add
        });
        this.eventBus.publish(`${this.eventName}:${eventType}`, target);
    }
}
