(function (paw, utils, Input, Popup) {
  function Fa2FormComponent($elt, popup) {
    this.localization;
    this.fa2Data;
    this.settings;

    this.$elt = $elt;
    this.popup = popup;

    this.inputFields = {};
    this.dataModel = {
      sendTo: "",
      sendToValue: "",
      token: "",
    };

    this.$submit = null;
    this.$form = null;
    this.$resendToken = null;
    this.$cancel = null;
    this.isResendLocked = true;

    this.resendPeriodLockHandler = null;
  }

  Fa2FormComponent.prototype.markupDef = function () {
    var html = [];
    html.push('<form id="fa2-settings-form" class="paw-holder">');
    html.push('   <div class="paw-area-v paw-nooverflow paw-holder">');
    html.push('      <div class="paw-col-d paw-scrollable paw-2fa-fields">');
    html.push('         <div class="paw-2fa-field row">');

    html.push('               <div class="paw-2fa-field-label col-md-3">');
    html.push(
      '                  <label for="fa2-telephone-number">' +
        this.localization.sendTo +
        "</label>"
    );
    html.push("               </div>");
    html.push('               <div class="col-md-9">');

    html.push(
      '                  <select id="mfa-send-to" class="form-control paw-selectpicker selectpicker" data-custom-class="paw-input-select">'
    );
    if (this.fa2Data.email) {
      html.push(
        "   <option value='MfaEmail'>" + this.fa2Data.email + "</option>"
      );
    }
    if (this.fa2Data.phoneNumber) {
      html.push(
        "   <option  value='MfaPhone'>" + this.fa2Data.phoneNumber + "</option>"
      );
    }
    if (this.fa2Data.viberPhone) {
      html.push(
        "   <option  value='MfaViberPhone'>" +
          this.localization.viber +
          " " +
          this.fa2Data.viberPhone +
          "</option>"
      );
    }
    html.push("</select>");
    html.push("               </div>");

    html.push("         </div>");
    html.push('         <div class="paw-2fa-field row">');
    html.push('            <div class="paw-2fa-field-label col-md-3">');
    html.push(
      '               <label for="fa2-token" class="">' +
        this.localization.token +
        "</label>"
    );
    html.push("            </div>");
    html.push('            <div class="col-md-9">');
    html.push(
      '               <input id="fa2-token" class="form-control" type="password" autocomplete="off" />'
    );
    html.push("            </div>");
    html.push("         </div>");
    html.push("         <div class='paw-2fa-form-error'><span></span></div>");
    html.push("      </div>");
    html.push(
      '      <div class="paw-col paw-area-h paw-items-middle paw-2fa-actions">'
    );
    html.push('         <div class="paw-col-d">');
    html.push("         </div>");
    html.push('         <div class="paw-col">');
    html.push(
      '               <button id="fa2-cancel" class="btn btn-outline paw-2fa-btn" type="button">'
    );
    html.push(
      "                  <span>" + this.localization.cancel + "</span>"
    );
    html.push("               </button>");
    html.push("         </div>");
    html.push('         <div class="paw-col">');
    html.push(
      '               <button id="fa2-resend-token" class="btn btn-outline paw-2fa-btn" type="button">'
    );
    html.push(
      "                  <span>" + this.localization.sendCode + "</span>"
    );
    html.push("               </button>");
    html.push("         </div>");
    html.push("         <div class='paw-col'>");
    html.push(
      '            <button id="fa2-auth" class="btn btn-primary" type="submit" disabled>'
    );
    html.push("               <span>" + this.localization.login + "</span>");
    html.push("            </button>");
    html.push("         </div>");
    html.push("      </div>");
    html.push("   </div>");
    html.push("</form>");

    return html;
  };

  Fa2FormComponent.prototype.init = function () {
    var self = this;
    this.$hours = $("#MFATokenValidHours");
    this.$submit = $("#fa2-auth");
    this.$form = $("#fa2-settings-form");
    this.$resendToken = $("#fa2-resend-token");
    this.$cancel = $("#fa2-cancel");

    var contactSet = false;
    if (utils.value.isSet(this.fa2Data.email)) {
      contactSet = true;
      this.dataModel.sendTo = "MfaEmail";
    } else if (utils.value.isSet(this.fa2Data.phoneNumber)) {
      contactSet = true;
      this.dataModel.sendTo = "MfaPhone";
    } else if (utils.value.isSet(this.fa2Data.viberPhone)) {
      contactSet = true;
      this.dataModel.sendTo = "MfaViberPhone";
    }
    this.setSendToValue();

    this.inputFields = {
      // phoneNumber: new Input(
      //   this.$elt.find("#fa2-telephone-number"),
      //   "phoneNumber",
      //   this.dataModel
      // ),
      // email: new Input(this.$elt.find("#fa2-email"), "email", this.dataModel),
      sendTo: new paw.com.Input(
        $("#mfa-send-to"),
        "sendTo",
        this.dataModel,
        {
          settings: {
            displayOnlySelectedKeys: true,
            selectionDisplayText: true,
          },
        },
        function () {
          self.setSendToValue();
        }
      ),
      token: new Input(
        this.$elt.find("#fa2-token"),
        "token",
        this.dataModel,
        undefined,
        function (e, val) {
          self.validateRequired(val);
          self.$elt.find(".paw-2fa-form-error > span").text("");
        }
      ),
    };

    this.$resendToken.on("click", function () {
      utils.async.asyncAction(function () {
        return self.resendToken();
      }, $(this));
    });

    this.$cancel.on("click", function () {
      self.popup.hide();
    });

    if (!contactSet) {
      this.lockResend();
    }

    this.$form.submit(function (e) {
      utils.async.asyncAction(function () {
        return self.fa2LoginFormSubmit(e);
      }, self.$submit);
    });
  };

  Fa2FormComponent.prototype.destroy = function () {
    this.$resendToken.off();
    if (utils.value.isSet(this.resendPeriodLockHandler)) {
      clearTimeout(this.resendPeriodLockHandler);
    }
  };

  Fa2FormComponent.prototype.resendToken = function () {
    var self = this;
    return utils.async
      .post(
        this.settings.send2FaCodeApiUrl,
        paw.lang.append(
          {
            SendTokenTo: this.dataModel.sendTo,
            SendToValue: this.dataModel.sendToValue,
          },
          this.settings.authModel() || {}
        )
      )
      .then(function (resp) {
        if (!resp.Valid) {
          switch (resp.Message) {
            case "PaymentRequired":
              self.openPaymentRequiredMsg();
              break;
            default:
              self.$elt.find(".paw-2fa-form-error > span").text(resp.Message);
              break;
          }
          return;
        } else {
          self.$elt.find(".paw-2fa-form-error > span").text("");
        }

        self.dataModel.token = "";
        self.inputFields.token.refreshValue();
        self.validateRequired(self.dataModel.token);

        self.resendPeriodLock();
      });
  };

  Fa2FormComponent.prototype.validateRequired = function (token) {
    var valid = utils.value.isSet(token) && token.length > 0;
    this.$submit.prop("disabled", !valid);
    return valid;
  };

  Fa2FormComponent.prototype.fa2LoginFormSubmit = function (e) {
    e.preventDefault();

    if (
      this.validateRequired(this.dataModel.token) &&
      this.validateRequired(this.dataModel.sendTo)
    ) {
      return this.submitToken(this.dataModel);
    }
  };

  Fa2FormComponent.prototype.lockResend = function () {
    this.$resendToken.prop("disabled", true);
    this.isResendLocked = true;
  };

  Fa2FormComponent.prototype.unlockResend = function () {
    this.$resendToken.prop("disabled", false);
    this.isResendLocked = false;
  };

  Fa2FormComponent.prototype.resendPeriodLock = function () {
    var self = this;
    this.lockResend();
    this.resendPeriodLockHandler = setTimeout(function () {
      if (
        utils.value.isSet(self.dataModel.phoneNumber) &&
        self.dataModel.phoneNumber.length > 0
      ) {
        self.unlockResend();
      }

      self.resendPeriodLockHandler = null;
    }, this.fa2Data.resendLockDuration * 1000);
  };

  Fa2FormComponent.prototype.submitToken = function (data) {
    var self = this;
    return utils.async
      .post(
        this.settings.submit2FaApiUrl,
        paw.lang.append(
          {
            Token: data.token,
            SendTokenTo: data.sendTo,
            SendToValue: data.sendToValue,
          },
          this.settings.authModel()
        )
      )
      .then(function (resp) {
        if (!resp.Valid) {
          self.settings.fa2Failed();
          self.$elt.find(".paw-2fa-form-error > span").text(resp.Message);
          return;
        }
        self.settings.fa2Completed();
      })
      .catch(function () {
        self.settings.fa2Failed();
      });
  };

  Fa2FormComponent.prototype.openPaymentRequiredMsg = function () {
    var self = this;
    var popup = new Popup("mfa-payment-required-msg", {
      maximizable: false,
      type: "error",
      message: self.localization.mfaPaymentRequired,
      styleClass: "paw-2fa-mfa-payment-required-popup",
      popupActions: [
        {
          id: "mfa-payment-required-cancel",
          label: this.localization.cancel,
          styleClass: "btn btn-outline",
          onSelected: function () {
            popup.hide();
          },
        },
        {
          id: "mfa-emessage-order",
          label: this.localization.order,
          onSelected: function () {
            var req = self.settings.encParamAuth
              ? utils.async.post(
                  "/Account/GetEncParameterAuth",
                  self.settings.authModel()
                )
              : utils.async.get("/Account/GetEncParameter");

            req.then(function (enc) {
              if (enc.IsSucess) {
                self.openEmsgOrderLink(enc.Enc);
              } else {
                self.openEmsgOrderLink();
              }
            });
          },
        },
      ],
    });
    popup.show();
  };

  Fa2FormComponent.prototype.openEmsgOrderLink = function (enc) {
    var link =
      this.localization.usiteUrl +
      "?ID=DMSLINK" +
      "&ENC=" +
      enc +
      "&show=eSporocanje";
    window.open(link, "_blank");
  };

  Fa2FormComponent.prototype.setSendToValue = function () {
    switch (this.dataModel.sendTo) {
      case "MfaEmail":
        this.dataModel.sendToValue = this.fa2Data.email;
        break;
      case "MfaPhone":
        this.dataModel.sendToValue = this.fa2Data.phoneNumber;
        break;
      case "MfaViberPhone":
        this.dataModel.sendToValue = this.fa2Data.viberPhone;
        break;
    }
  };

  paw.com.fa2.Fa2FormComponent = Fa2FormComponent;
})(paw, paw.utils, paw.com.Input, paw.com.Popup);
