(function (paw, utils, Popup, HostSupportSessionsComponent) {
  var hostRes = null;
  var loginModel = null;
  var selectedSession = null;
  var partnerUser = null;
  var loginInProgress = false;

  var sqlLoginTmp = {
    username: "",
    domain: "",
  };

  function HostSupportLogin(loginControls, settings, localization) {
    this.loginControls = paw.lang.append(
      {
        $authType: undefined,
        $username: undefined,
        $password: undefined,
        $domain: undefined,
        $submit: undefined,
        $form: undefined,
        $supportLoginForm: undefined,
        $hostSupportServer: undefined,
        $hostSupportDatabase: undefined,
        $inputHostSupportCompany: undefined,
        $hostSupportRequestId: undefined,
        $hostSupportPartnerUser: undefined,
        $hostSupportLoginLink: undefined,
      },
      loginControls
    );

    this.settings = paw.lang.append(
      {
        sessionsApiUrl: undefined,
        hostSupportApiUrl: undefined,
        hostSupportLoginApiUrl: undefined,
        loginUrl: undefined,
      },
      settings || {}
    );

    this.localization = paw.lang.append(
      {
        cloudSupportLogin: "@Loc.CloudSupportLogin",
        getRequests: "@Loc.GetRequests",
        open: "@Loc.Open",
        cancel: "@Loc.Cancel",
        company: "@Loc.Company",
        uid: "@Loc.UID",
        user: "@Loc.User",
        datetime: "@Loc.DateTime",
        databases: "@Loc.Databases",
        credentialsRequired: "@Loc.HostSupportPartnerCredentialsRequired",
        noDatabasesAvailableForConnection:
          "@Loc.NoDatabasesAvailableForConnection",
        filters: "@Loc.Filters",
        clear: "@Loc.Clear",
        search: "@Loc.Search",
        searchFind: "@Loc.SearchFind",
        database: "@Loc.Database",
        all: "@Loc.All",
        support: "@Loc.Support",
        show: "@Loc.Show",
        login: "@Loc.Login",
        username: "@Loc.UserName",
        password: "@Loc.Password",
      },
      localization || {}
    );

    this.isProceed = false;
  }

  HostSupportLogin.prototype.init = function () {
    var self = this;
    // skip host support initialization (not allowed or non-hosted)
    if (
      utils.value.strToBool(this.loginControls.$allowHostSupportLogin.val()) !==
      true
    ) {
      return;
    }

    this.loginControls.$hostSupportLoginLink.on("click", function () {
      self.start();
    });
  };

  HostSupportLogin.prototype.activate = function () {
    sqlLoginTmp.username = this.loginControls.$username.val();
    sqlLoginTmp.domain = this.loginControls.$domain.val();
    this.lockLoginForm();
  };

  HostSupportLogin.prototype.lockLoginForm = function () {
    this.loginControls.$authType.val("HostSupportAuth");
    this.loginControls.$username.attr("type", "password");
    this.populateLoginForm({
      Username: "",
      Password: "",
      Company: "",
      SupportRequestID: null,
      PartnerUser: null,
    });
  };

  HostSupportLogin.prototype.deactivate = function () {
    this.loginControls.$authType.val("SQLAuth");
    this.loginControls.$username.attr("type", "text");

    // clear credentials in case they were populated by host support
    this.loginControls.$domain.val(sqlLoginTmp.domain);
    this.loginControls.$username.val(sqlLoginTmp.username);
    this.loginControls.$password.val("");
    sqlLoginTmp.domain = "";
    sqlLoginTmp.username = "";

    this.isProceed = false;
  };

  HostSupportLogin.prototype.start = function () {
    var self = this;
    this.activate();
    this.popup = new Popup("host-support-login-popup", {
      Component: HostSupportSessionsComponent,
      title: this.localization.support,
      styleClass: "host-support-sessions-popup",
      contentStyleClass: "paw-holder",
      bind: {
        localization: this.localization,
        settings: {
          sessionsApiUrl: this.settings.sessionsApiUrl,
          onFetchSessions: function (res) {
            if (res.Error) {
              self.showErrorMessage("cloud-support-activate-error", res.Error);
              return;
            }
            return res;
          },
          onOpen: function (session, partnerUsername) {
            if (loginInProgress) {
              console.error("Login already in progress...");
              return utils.async.promise();
            }
            selectedSession = session;
            partnerUser = partnerUsername;
            return utils.async
              .post(self.settings.hostSupportApiUrl, {
                SupportRequestID: selectedSession.SupportRequestID,
              })
              .then(function (res) {
                if (res.Error) {
                  self.showErrorMessage(
                    "cloud-support-host-support",
                    res.Error
                  );
                  return;
                }
                hostRes = res;
                self.isProceed = true;
                if (self.openLoginForm()) {
                  loginInProgress = true;
                  self.loginControls.$form.submit();
                  return;
                }
                self.showErrorMessage(
                  "cloud-support-host-support-form",
                  self.localization.noDatabasesAvailableForConnection
                );
              });
          },
          onCancel: function () {
            self.popup.hide();
          },
          resetData: function () {
            hostRes = null;
            selectedSession = null;
            partnerUser = null;
          },
        },
      },
      onClose: function () {
        if (!self.isProceed) {
          self.deactivate();
        }
        hostRes = null;
        loginModel = null;
        selectedSession = null;
        partnerUser = null;
      },
    });
    this.popup.show();
  };

  HostSupportLogin.prototype.showErrorMessage = function (popupId, message) {
    var errorPopup = new Popup(popupId, {
      type: "error",
      maximizable: false,
      contentStyleClass: "p-3x",
      markupDef: function () {
        return ['<div class="p-3x">' + message + "</div>"];
      },
    });
    errorPopup.show();
    return errorPopup;
  };

  HostSupportLogin.prototype.openLoginForm = function () {
    if (hostRes.Databases.length === 0) {
      console.error("No databases for selected session...");
      return false;
    }
    var db = hostRes.Databases[0];
    this.prepareLoginModel({
      HostUser: db.HostUser,
      HostP: db.HostP,
      HostServer: db.HostServer,
      Database: db.Database,
      Company: db.DatabaseName,
      SupportRequestID: selectedSession.SupportRequestID,
      PartnerUser: partnerUser,
    });
    this.populateLoginForm(loginModel);
    this.loginControls.$submit.removeAttr("disabled");
    return true;
  };

  HostSupportLogin.prototype.prepareLoginModel = function (model) {
    loginModel = {
      Username: model.HostUser,
      Password: model.HostP,
      Company: model.Company,
      HostServer: model.HostServer,
      Database: model.DatabaseName,
      SupportRequestID: model.SupportRequestID,
      PartnerUser: model.PartnerUser,
    };
  };

  HostSupportLogin.prototype.populateLoginForm = function (data) {
    this.loginControls.$username.val(data.Username);
    this.loginControls.$password.val(data.Password);
    this.loginControls.$domain.val(data.Company);
    this.loginControls.$hostSupportServer.val(data.HostServer);
    this.loginControls.$hostSupportDatabase.val(data.Database);
    this.loginControls.$inputHostSupportCompany.val(data.Company);
    this.loginControls.$hostSupportRequestId.val(data.SupportRequestID);
    this.loginControls.$hostSupportRequestId.val(data.SupportRequestID);
    this.loginControls.$hostSupportPartnerUser.val(data.PartnerUser);
  };

  paw.com.login.hostSupport.HostSupportLogin = HostSupportLogin;
})(
  paw,
  paw.utils,
  paw.com.Popup,
  paw.com.login.hostSupport.HostSupportSessionsComponent
);
