/// 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) {
            PDJS.Shared.MessageStack.instance.success("Rules Saved Successfully!");
            editor.content(result.content);
            editor.focus();
        }, (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);
                    }
                });

                Jade.UI.ErrorDialog.open({
                    dialogStyle: Jade.UI.MessageDialogStyle.Error,
                    dialogButtons: Jade.UI.MessageDialogButtonStyle.OK,
                    message: "The following errors were found during compilation:",
                    errors: errors,
                    select: (e) => {
                        e.close();
                        editor.focus();
                    }
                });

            }

        });

    }

});