/// class PD.Web.UI.MutationSource

PD.Web.UI.MutationSource =
Class.extend({

    //================================
    // FIELDS
    //================================

    _isDirty: null,
    
    //================================
    // CONSTRUCTOR
    //================================

    init: function (options) {
        this._options = options;
        this._isDirty = false;
        this._monitors = new PD.BCL.List();
        this._registerMonitors();
        this.startMonitors();
    },

    //================================
    // PROPERTIES
    //================================

    get_isDirty: function () {
        return this._isDirty;
    },

    get_options: function (id, defaultValue) {

        var result = null;

        if (id !== undefined) {
            result = this._options[id];
            if (result === undefined) {
                result = defaultValue;
            }
        }
        else {
            result = this._options;
        }

        return result;
    },

    get_monitors: function () {
        return this._monitors;
    },

    get_id: function () {
        return this.get_options("id");
    },

    get_name: function () {

        var result = this.get_options("name", this.get_options("id"));

        if (_.isFunction(result)) {
            result = result();
        }

        return result;

    },

    //================================
    // PUBLIC METHODS
    //================================
    
    startMonitors: function () {
        this.get_monitors().each(function (index, monitor) {
            monitor.start();
        });
    },

    stopMonitors: function () {
        this.get_monitors().each(function (index, monitor) {
            monitor.stop();
        });
    },

    resolve: function (success, error) {

        var that = this,
            defaultFn = function (success, error) {
                error();
            };

        $.proxy(this.get_options("resolve", defaultFn), this)(function () {
            that.setClean();
            success();
        }, error);

    },

    setClean: function () {

        var callback = this.get_options("onClean");

        this._isDirty = false;

        if (_.isFunction(callback)) {
            callback();
        }

    },

    setDirty: function () {

        var callback = this.get_options("onDirty");

        this._isDirty = true;

        if (_.isFunction(callback)) {
            callback();
        }

    },

    //================================
    // PRIVATE METHODS
    //================================

    _registerMonitors: function () {

        var that = this,
            monitors = this.get_options("monitors", []);

        monitors = new PD.BCL.List(monitors);

        this.get_monitors().clear();

        monitors.each(function (index, monitor) {
            monitor.load(that);
            that.get_monitors().add(monitor);
        });

    }

});