(function (paw, utils, Popup, SessionsDatagrid, SessionsFilters) {
  function HostSupportSessionsComponent($elt) {
    this.localization;
    this.settings;

    this.$elt = $elt;

    this.$openBtn = null;
    this.$cancelBtn = null;
    this.$getSessionsBtn = null;

    this.sessions = [];
    this.companies = [];
    this.users = [];
    this.databases = [];

    this.selectedId = null;
    this.partnerUser = null;

    this.findOnChange = true;

    this.grid = null;
    this.filters = null;
  }

  HostSupportSessionsComponent.prototype.markupDef = function () {
    var markup = [];
    markup.push('<div class="paw-area-v paw-holder host-support-sessions">');
    markup.push(
      '   <div class="paw-col p-3x host-support-credentials-holder">'
    );
    markup.push(
      '      <form id="host-sessions-form" class="paw-area-h paw-items-middle">'
    );
    markup.push('         <div class="paw-col-d paw-area-h paw-items-middle">');
    markup.push(
      '            <div class="paw-col p-r-3x paw-area-h paw-items-middle">'
    );
    markup.push('               <div class="paw-col p-r-3x">');
    markup.push(
      '                 <label for="PartnerUsername">' +
        this.localization.username +
        "</label>"
    );
    markup.push("                  </div>");
    markup.push("                  <div class=paw-col-d>");
    markup.push(
      '                  <input id="PartnerUsername" class="form-control host-support-input host-support-rounded" type="text" autocomplete="off" />'
    );
    markup.push("                  </div>");
    markup.push("               </div>");
    markup.push(
      '            <div class="paw-col paw-area-h paw-items-middle">'
    );
    markup.push('               <div class="paw-col p-r-3x">');
    markup.push(
      '                 <label for="PartnerPassword">' +
        this.localization.password +
        " </label>"
    );
    markup.push("               </div>");
    markup.push('               <div class="paw-col">');
    markup.push(
      '                 <input id="PartnerPassword" class="form-control host-support-input host-support-rounded" type="password" autocomplete="off" />'
    );
    markup.push("               </div>");
    markup.push("            </div>");
    markup.push("         </div>");
    markup.push('         <div class="paw-col">');
    markup.push(
      '            <button id="get-requested-sessions" class="btn btn-success host-support-rounded" type="submit"><span>' +
        this.localization.show +
        "</span></button>"
    );
    markup.push("         </div>");
    markup.push("      </form>");
    markup.push("   </div>");
    markup.push(
      '   <div class="paw-col paw-area-h paw-items-middle paw-finder-filters paw-nooverflow p-3x">'
    );
    markup.push(
      '      <div class="paw-col-d paw-area-h paw-finder-pinned-filters paw-nooverflow"></div>'
    );
    markup.push('      <div class="paw-col paw-finder-filters-holder">');
    markup.push(
      '         <button id="support-sessions-filters" class="btn btn-primary btn-outline btn-nav">'
    );
    markup.push('            <span class="fa fa-filter"></span>');
    markup.push(
      '            <span class="paw-finder-filters-label">' +
        this.localization.filters +
        "</span>"
    );
    markup.push("         </button>");
    markup.push("      </div>");
    markup.push("   </div>");
    markup.push('   <div class="paw-col-d paw-nooverflow">');
    markup.push(
      '      <div class="paw-host-support-sessions-datatable paw-holder paw-nooverflow"></div>'
    );
    markup.push("   </div>");
    markup.push('   <div class="paw-col paw-area-h p-3x">');
    markup.push('      <div class="paw-col-d"></div>');
    markup.push('      <div class="paw-col">');
    markup.push(
      '         <button id="host-support-login-cancel" class="btn host-support-rounded btn-outline" type="button"><span>' +
        this.localization.cancel +
        "</span></button>"
    );
    markup.push(
      '         <button id="host-support-login-open" class="btn btn-success host-support-rounded" type="button" disabled><span>' +
        this.localization.login +
        "</span></button>"
    );

    markup.push("      </div>");
    markup.push("   </div>");
    markup.push("</div>");
    return markup;
  };

  HostSupportSessionsComponent.prototype.init = function () {
    var self = this;

    this.grid = new SessionsDatagrid(this);
    this.filters = new SessionsFilters(this);

    this.filters.init();
    this.grid.init();

    this.$requestSessionsBtn = $("#get-requested-sessions");
    this.$openBtn = this.$elt.find("#host-support-login-open");
    this.$cancelBtn = this.$elt.find("#host-support-login-cancel");
    this.$hostSessionsForm = this.$elt.find("form#host-sessions-form");
    this.$hostSessionsForm.submit(function (e) {
      e.preventDefault();

      utils.async.asyncAction(function () {
        return self.fetchSessions();
      }, self.$requestSessionsBtn);
    });

    this.$openBtn.on("click", function () {
      if (utils.value.isFunction(self.settings.onOpen)) {
        utils.async.asyncAction(
          function () {
            self.settings.onOpen(self.selectedSession, self.partnerUser);
          },
          self.$openBtn,
          null,
          true
        );
      }
    });

    this.$cancelBtn.on("click", function () {
      if (utils.value.isFunction(self.settings.onCancel)) {
        self.settings.onCancel();
      }
    });
  };

  HostSupportSessionsComponent.prototype.destroy = function () {
    this.$hostSessionsForm.off();
    this.$openBtn.off();
    this.$cancelBtn.off();

    this.grid.destroy();
    this.filters.destroy();
  };

  HostSupportSessionsComponent.prototype.fetchSessions = function () {
    var self = this;
    if (utils.value.isFunction(this.settings.onFetchSessions)) {
      this.resetData();

      this.$openBtn.attr("disabled", true);

      var username = $("#PartnerUsername").val();
      this.partnerUser = username;
      var password = $("#PartnerPassword").val();
      if (!this.validateCredentials(username, password)) {
        return utils.async.promise();
      }
      return utils.async
        .post(this.settings.sessionsApiUrl, {
          username: $("#PartnerUsername").val(),
          password: $("#PartnerPassword").val(),
        })
        .then(function (payload) {
          var res = self.settings.onFetchSessions(payload);
          if (!utils.value.isSet(res) || res.Error) {
            self.sessions = [];
            return;
          }
          self.compileSessionsData(res);
          self.filters.compileFilterData();
          self.filterSessions();
        });
    }
  };

  HostSupportSessionsComponent.prototype.compileSessionsData = function (res) {
    var self = this;
    self.sessions = utils.iterable.map(res.ClientRequests, function (item, i) {
      return {
        Company: item.UserCompany,
        Uid: item.UserPA_UID,
        User: item.UsersiteUser,
        DateTime: item.RequestInsertDateTime,
        Databases: item.Databases.join(", "),
        SupportRequestID: item.SupportRequestID,
        OrderIndex: i,
      };
    });

    self.companies = [];
    self.users = [];
    self.databases = [];

    utils.iterable.iterate(self.sessions, function (item) {
      var comp = utils.value.trimString(item.Company);
      var usr = utils.value.trimString(item.User);
      if (self.companies.indexOf(comp) === -1) {
        self.companies.push(comp);
      }
      if (self.users.indexOf(usr) === -1) {
        self.users.push(usr);
      }

      var dbList = item.Databases.split(",");
      utils.iterable.iterate(dbList, function (db) {
        db = utils.value.trimString(db);
        if (self.databases.indexOf(db) === -1) {
          self.databases.push(db);
        }
      });
    });
    self.companies.sort(function (a, b) {
      if (a > b) {
        return 1;
      }
      if (a < b) {
        return -1;
      }
      return 0;
    });
    self.users.sort(function (a, b) {
      if (a > b) {
        return 1;
      }
      if (a < b) {
        return -1;
      }
      return 0;
    });
    self.databases.sort(function (a, b) {
      if (a > b) {
        return 1;
      }
      if (a < b) {
        return -1;
      }
      return 0;
    });
  };

  HostSupportSessionsComponent.prototype.validateCredentials = function (
    username,
    password
  ) {
    if (
      !utils.value.isSet(username) ||
      username.length === 0 ||
      !utils.value.isSet(password) ||
      password.length === 0
    ) {
      var errorPopup = new Popup("partner-credentials-error", {
        type: "error",
        maximizable: false,
        contentStyleClass: "p-3x",
        markupDef: function () {
          return [
            '<div class="p-3x">' +
              self.localization.credentialsRequired +
              "</div>",
          ];
        },
      });
      errorPopup.show();
      return false;
    }
    return true;
  };

  HostSupportSessionsComponent.prototype.onResize = function () {
    this.grid.resize();
  };

  HostSupportSessionsComponent.prototype.filterSessions = function () {
    var self = this;
    if (!this.findOnChange) {
      return;
    }

    var filtered = utils.iterable.filter(this.sessions, function (item) {
      var search =
        self.filters.filterModel.search.length > 0
          ? item.Company.toLowerCase().includes(
              self.filters.filterModel.search
            ) ||
            item.Uid.toLowerCase().includes(self.filters.filterModel.search) ||
            item.User.toLowerCase().includes(self.filters.filterModel.search) ||
            item.Databases.toLowerCase().includes(
              self.filters.filterModel.search
            )
          : true;
      var company =
        self.filters.filterModel.company.length > 0
          ? self.filters.filterModel.company.indexOf(
              utils.value.strReplace(
                utils.value.trimString(item.Company),
                " ",
                "_"
              )
            ) > -1
          : true;
      var user =
        self.filters.filterModel.user.length > 0
          ? self.filters.filterModel.user.indexOf(
              utils.value.strReplace(
                utils.value.trimString(item.User),
                " ",
                "_"
              )
            ) > -1
          : true;

      var dbs = item.Databases.split(",");
      var database = self.filters.filterModel.database.length === 0;
      if (!database) {
        utils.iterable.iterate(dbs, function (db) {
          if (
            self.filters.filterModel.database.indexOf(
              utils.value.strReplace(utils.value.trimString(db), " ", "_")
            ) > -1
          ) {
            database = true;
            return false;
          }
        });
      }
      return search && company && user && database;
    });
    this.grid.loadData(filtered);
  };

  HostSupportSessionsComponent.prototype.resetData = function () {
    this.sessions = [];
    this.companies = [];
    this.users = [];
    this.databases = [];
    this.grid.loadData([]);
    this.filters.unload();

    this.selectedId = null;
    this.settings.resetData();
  };

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