/// class PD.Manage.Modules.Rules.RuleScriptSaveCommand
// using PD.Commands.Command

PD.Manage.Modules.Rules.RuleScriptSaveCommand =
PD.Commands.Command.extend({

    //===================================
    // PUBLIC METHODS
    //===================================

    setDefaults: function () {
        this._super();
        this.props("id", "rule-script/save");
        this.props("label", "Save");
        this.props("enabled", true);
        this.props("icon", PD.Path.to16x16("floppy_disk.png"));
        this.props("canExecute", true);

        this.state("ruleScriptId", null);
        this.state("editor", null);

    },

    setState: function (state) {
        this._super(state);
    },

    execute: function (e) {
        this._super(e);

        var that = this,
            ruleScriptId = this.state("ruleScriptId"),
            editor = this.state("editor"),
            service = new PD.Manage.Services.RulesService();

        editor.clearMarkers();

        service.saveRuleScript(ruleScriptId, editor.content(), function (result) {
            PD.messageStack.success("Rules Saved Successfully!");
            editor.content(result.content);
            editor.focus();
        }, function (e) {

            var errors = e.responseJSON;

            if (errors != null) {

                e.errorHandled = true;

                // add line error markers
                _.each(errors, function (err) {
                    if (err.tags != null && ("ScriptLine" in err.tags)) {
                        editor.addMarker(err.message, err.tags["ScriptLine"] - 1);
                    }
                });

                PD.Web.UI.ErrorDialog.show({
                    title: "Rule Compilation Error",
                    message: "The following errors were found during compilation:",
                    errors: errors,
                    buttons: [
                        {
                            label: "OK",
                            callback: function (e) {
                                e.close();
                                editor.focus();
                            }
                        }
                    ]
                });

            }

        });

    }

});