/// class PD.Manage.ModuleCollection

PD.Manage.ModuleCollection = Class.extend({

    _collection: null,

    init: function (options) {
        this._collection = [];
    },

    findById: function (id) {

        var result = null;

        result = _.find(this._collection, function (item) {
            return item.data("id") === id;
        });

        return result;

    },

    add: function (module) {
        var moduleId = module.data("id");
        if (this.findById(moduleId) == null) {
            this._collection.splice(0, 0, module);
        }
    },

    remove: function (id) {

        var removeAtIndex = null;

        result = _.find(this._collection, function (item, index) {
            removeAtIndex = index;
            return item.data("id") === id;
        });

        if (removeAtIndex != null) {
            this._collection.splice(removeAtIndex, 1);
        }

        return result;

    },

    getFallback: function (id) {
        
        var result = null,
            fallbackIndex = -1;

        _.find(this._collection, function (item, index) {
            var found = item.data("id") === id;
            if (found === true) {
                fallbackIndex = (index === 0 ? 1 : index - 1);
            }
            return found;
        });

        if (this._collection.length > fallbackIndex) {
            result = this._collection[fallbackIndex];
        }

        return result;

    },

    each: function (fn) {
        
        if (_.isFunction(fn)) {
            _.each(this._collection, function (module) {
                fn(module);
            });
        }

    },

    count: function () {
        return this._collection.length;
    },

    changeId: function (oldId, newId) {

        let module = this.findById(oldId);

        if (module) {
            module.data("id", newId);
        }
        
    }

});