fcf.module({
  name: "fcfDBControls:templates/management.wrapper.js",
  dependencies: ["fcf:NClient/Wrapper.js"],
  module: function(Wrapper){
    return class WrapperEx extends Wrapper{

      constructor(a_initializeOptions){
        super(a_initializeOptions);
      }

      async onEdit(){
        let formArguments = {
          fcfAlias:   "form",
          mode:       "edit",
          projection: this.getArg("projection"),
          key:        this.getArg("key"),
        };
        if (this.getArg("editFields"))
          formArguments.fields = this.getArg("editFields");

        this.getChild("edit").lock();

        let buttons = [];
        buttons.push(fcf.argTmpl("@controls:button", {title: fcf.t("Ok"), fcfEventClick: "parent.getParent().onEditComplete(parent)"}));
        if (this.getArg("enableEditWithoutClose"))
          buttons.push(fcf.argTmpl("@controls:button", {title: fcf.t("Save only"), fcfEventClick: "parent.getParent().onEditCompleteWithoutClose(parent)"}));
        buttons.push(fcf.argTmpl("@controls:button", {title: fcf.t("Cancel"), fcfEventClick: "parent.close('cancel')" }));

        await fcf.application.render({
          template: "@controls:dialog",
          parent: this,
          owner:  document.body,
          args: {
            fcfClass: "fcf-db-controls-management-dialog",
            title: fcf.t("Editing an entry"),
            content: fcf.argTmpl("@dbcontrols:form",  formArguments),
            buttons: fcf.argVal(buttons),
          }
        });

        this.getChild("edit").unlock();
      }

      onEditComplete(a_dialog) {
        let self = this;
        let errors = a_dialog.getChild("form").check();
        if (!fcf.empty(errors)){
          a_dialog.getChild("form").setArg("alerts", []);
          a_dialog.getChild("form").setArg("errors", errors);
          return;
        }
        a_dialog.lock();
        a_dialog.getChild("form").write()
        .then(()=>{
          if (self.getArg("reloadPage"))
            location.reload();
          a_dialog.close("ok");
        })
        .catch((a_error)=>{
          a_dialog.getChild("form").setArg("alerts", [a_error]);
          a_dialog.getChild("form").setArg("errors", []);
          fcf.application.getEventChannel().send("fcf_error", {error: a_error});
        })
        .finally(()=>{
          a_dialog.unlock();
        })
      }

      onEditCompleteWithoutClose(a_dialog) {
        let self = this;
        let errors = a_dialog.getChild("form").check();
        if (!fcf.empty(errors)){
          a_dialog.getChild("form").setArg("alerts", []);
          a_dialog.getChild("form").setArg("errors", errors);
          return;
        }
        a_dialog.lock();
        a_dialog.getChild("form").write()
        .catch((a_error)=>{
          a_dialog.getChild("form").setArg("alerts", [a_error]);
          a_dialog.getChild("form").setArg("errors", []);
          fcf.application.getEventChannel().send("fcf_error", {error: a_error});
        })
        .finally(()=>{
          a_dialog.unlock();
        })
      }

      async onNew(){
        let formArgs     = {
          fcfAlias:     "form",
          mode:         "add",
          projection:   this.getArg("projection"),
        };
        if (!fcf.empty(this.getArg("addFormArgValue")))
          formArgs.value = this.getArg("addFormArgValue");

        this.getChild("new").lock();

        await fcf.application.render({
          template: "@controls:dialog",
          parent: this,
          owner:  document.body,
          args: {
            fcfClass:       "fcf-db-controls-management-dialog",
            title:          fcf.t("Adding an entry"),
            content:        fcf.argTmpl("@dbcontrols:form", formArgs),
            buttons:      fcf.argVal([
              fcf.argTmpl("@controls:button", { title: fcf.t("Create"), fcfEventClick: "parent.getParent().onNewComplete(parent)"} ),
              fcf.argTmpl("@controls:button", { title: fcf.t("Cancel"), fcfEventClick: "parent.close('close')"} ),
            ]),
          }
        })

        this.getChild("new").unlock();
      }

      onNewComplete(a_dialog){
        let self = this;
        let form = a_dialog.getChild("form");

        let errors = a_dialog.getChild("form").check();
        if (!fcf.empty(errors)){
          a_dialog.getChild("form").setArg("alerts", []);
          a_dialog.getChild("form").setArg("errors", errors);
          return;
        }

        a_dialog.lock();
        return form.write()
        .then(()=>{
          if (self.getArg("reloadPage"))
            location.reload();
          a_dialog.close();
        })
        .catch((a_error)=>{
          a_dialog.getChild("form").setArg("alerts", [a_error]);
          a_dialog.getChild("form").setArg("errors", []);
          fcf.application.getEventChannel().send("fcf_error", {error: a_error});
        })
        .finally(()=>{
          a_dialog.unlock();
        })
      }

      async onRemove(){
        this.getChild("delete").lock();
        await fcf.application.render({
          template: "@controls:dialog",
          parent: this,
          owner:  document.body,
          args: {
            title:        fcf.t("Record deletion"),
            content:      fcf.t("To remove record?"),
            buttons:      fcf.argVal([
              fcf.argTmpl("@controls:button", { title: fcf.t("Remove"),    fcfEventClick: "parent.getParent().onRemoveComplate(parent, '" + fcf.escapeQuotes(this.getArg("key")) + "')"} ),
              fcf.argTmpl("@controls:button", { title: fcf.t("Cancel"),    fcfEventClick: "parent.close('cancel')"} ),
            ]),
          }
        });
        this.getChild("delete").unlock();
      }

      onRemoveComplate(a_dialog, a_recordId){
        let self = this;
        a_dialog.lock();
        this.send({action: "remove", id: a_recordId, projection: this.getArg("projection")})
        .then(()=>{
          if (self.getArg("transitionAfterRemoval"))
            window.location = self.getArg("transitionAfterRemoval");
          else if (self.getArg("reloadPage"))
            location.reload();
          a_dialog.close("ok");
        })
        .catch((a_error)=>{
          fcf.application.getEventChannel().send("fcf_error", {error: a_error});
        })
        .finally(()=>{
          a_dialog.unlock();
        })
      }

    };
  }
});
