fcf.module({
  name: "fcfSimpleAuthorization:templates/signin-form.wrapper.js",
  dependencies: ["fcfControls:templates/form.wrapper.js", "fcfSimpleAuthorization:Client.js"],
  module: function(FormWrapper, client){

    fcf.addException("FAILD_FORM_INPUT", "The form was filled out incorrectly");

    return class SigninWrapper extends FormWrapper{
      constructor(a_initializeOptions) {
        super(a_initializeOptions);
      }

      onArg (a_argName, a_value, a_editor, a_isInnerCall, a_suffix) {
      }

      onArgError (a_value) {
        this.update();
      }

      onRegistration() {
        client.createRegistrationDialog();
      }

      onLoginByEmail() {
        fcf.application.render({
          template: "@controls:dialog",
          parent:   this,
          owner:    document.body,
          args: {
            fcfStyle: "width: 350px",
            title:    fcf.t("Log in by email"),
            content:  fcf.argTmpl("fcfSimpleAuthorization:templates/login-by-email.tmpl", {fcfAlias: "form"}),
            buttons:  fcf.argVal([
              fcf.argTmpl("@controls:button", {fcfAlias: "ok", title: "!{{Ok}}!", fcfEventClick: "parent.getParent().onLoginByEmailComplete(parent)"}),
              fcf.argTmpl("@controls:button", {fcfAlias: "cancel", title: "!{{Cancel}}!", fcfEventClick: "parent.close('cancel')"}),
            ])
            
          }
        })
      }

      onLoginByEmailComplete(a_dialog){
        let form  = a_dialog.getChild("form");
        if (form.getArg("confirmationMode")){
          a_dialog.close("ok");
          return;
        }
        let value  = fcf.trim(form.getArg("value"));
        if (fcf.empty(value)){
          form.setArg("error", fcf.t("Username and email not specified"));
          return;
        }
        form.sendEmail()
        .then(()=>{
          a_dialog.getChild("cancel").setArg("fcfStyle", "display: none");
        })
      }

      signin() {
        let self = this;
        let errors = this.check();
        if (!fcf.empty(errors)) {
          this.setArg("errors", errors);
          this.setArg("error", undefined);
          return fcf.actions().error(new fcf.Exception("FAILD_FORM_INPUT"));
        }

        let value = this.getArg("value");
        return fcf.load({
          path: "/fcfpackages/fcf/login",
          post: {user: value.user, password: value.password }
        })
        .then((a_sessionId)=>{
          fcf.getContext().session.id = a_sessionId;
          fcf.saveContext();
          return true;
        })
        .catch((a_error)=>{
          self.setArg("errors", errors);
          self.setArg("error", a_error);
        })
      }

    };
  }
});
