(function (paw, utils) {
  function HostSupportSessionsGrid(context) {
    this.context = context;

    this.gridColumns = [
      {
        id: "Company",
        label: this.context.localization.company,
      },
      {
        id: "Uid",
        label: this.context.localization.uid,
      },
      {
        id: "User",
        label: this.context.localization.user,
      },
      {
        id: "DateTime",
        label: this.context.localization.datetime,
      },
      {
        id: "Databases",
        label: this.context.localization.databases,
      },
    ];

    this.$datatableHolder = null;
    this.datatable = null;
  }

  HostSupportSessionsGrid.prototype.markupDef = function () {
    var self = this;
    var markup = [];

    markup.push(
      '<table id="host-support-sessions-datatable" class="host-support-table">'
    );
    markup.push("   <thead>");
    markup.push("      <tr>");
    markup.push("        <th class='host-support-row-select'></th>");
    utils.iterable.iterate(this.gridColumns, function (col) {
      var headerAttrs = "";
      if (utils.value.isSet(col.width)) {
        headerAttrs += ' width="' + col.width + '"';
      }
      markup.push("<th class='' " + headerAttrs + ">");
      markup.push(col.label);
      markup.push("</th>");
    });
    markup.push("        <th></th>");
    markup.push("      </tr>");
    markup.push("   </thead>");
    markup.push("   <tbody class=''></tbody");
    markup.push("</div>");
    return markup;
  };

  HostSupportSessionsGrid.prototype.init = function () {
    var self = this;
    this.$datatableHolder = this.context.$elt.find(
      ".paw-host-support-sessions-datatable"
    );
    this.$datatableHolder.html(this.markupDef().join("\n"));

    var cols = utils.iterable.map(this.gridColumns, function (colDef) {
      return {
        data: colDef.id,
      };
    });
    var $dt = this.$datatableHolder.find("table");
    var d = utils.async.defer();
    var columns = [
      {
        data: null,
        orderable: false,
        className: "dt-body-center",
        render: function (data, type, row) {
          return (
            "<div class='checkbox-border'><input id='row-select-" +
            data +
            "' type='checkbox'" +
            "class='ackey selector row-selection' name='select' value='" +
            data +
            "'" +
            (data === true || data === "T" ? "' checked='" + data + "'" : "") +
            " data-req-id='" +
            row.SupportRequestID +
            "'></div>"
          );
        },
      },
    ].concat(cols);
    this.datatable = $dt.DataTable({
      paging: false,
      searching: false,
      responsive: false,
      info: false,
      processing: true,
      serverSide: false,
      autoWidth: false,
      ajax: "",
      deferLoading: 0,
      columns: columns.concat([
        { id: "OrderIndex", visible: false, data: "OrderIndex" },
      ]),
      columnDefs: [
        {
          targets: 4,
          orderData: 6,
        },
        {
          targets: 6,
        },
      ],
      stateSave: false,
      stateSaveCallback: undefined,
      stateLoadCallback: undefined,
      fixedHeader: true,
      scrollX: true,
      scrollY: true,
      scrollCollapse: true,
      order: [[4, "asc"]],
      initComplete: function () {
        self.datagridHeightCalc();
        d.resolve();
      },
      fixedColumns: {
        leftColumns: 1,
      },
    });

    this.datatable.on("draw", function () {
      $dt.on("change", ".row-selection", function () {
        self.$datatableHolder.find("tr.active").removeClass("active");
        self.$datatableHolder.find(".row-selection").prop("checked", false);
        self.context.selectedId = utils.value.strToNum(
          $(this).attr("data-req-id")
        );
        $(this).prop("checked", true);
        self.context.selectedSession = utils.iterable.get(
          self.context.sessions,
          function (session) {
            return session.SupportRequestID === self.context.selectedId;
          }
        );
        self.context.$openBtn.removeAttr("disabled");
        $(this).closest("tr").addClass("active");
      });

      self.$datatableHolder.find('input[type="checkbox"]').customCheckbox();
    });
    return d.promise;
  };

  HostSupportSessionsGrid.prototype.destroy = function () {
    if (this.datatable) {
      this.datatable.destroy();
    }
  };

  HostSupportSessionsGrid.prototype.loadData = function (sessions) {
    var self = this;
    self.datatable.clear().rows.add(sessions).draw();
  };

  HostSupportSessionsGrid.prototype.datagridHeightCalc = function () {
    var headerHeight = this.$datatableHolder
      .find(".dataTables_scrollHead")
      .outerHeight(true); // Get the header height
    var viewportHeight = this.$datatableHolder.innerHeight(); // Get total viewport height
    var newTableHeight = viewportHeight - headerHeight; // Adjust for spacing
    this.$datatableHolder
      .find(".dataTables_wrapper .dataTables_scrollBody")
      .css({
        "max-height": newTableHeight + "px",
        height: newTableHeight + "px",
      });
  };

  HostSupportSessionsGrid.prototype.resize = function () {
    if (!utils.value.isSet(this.datatable)) {
      return;
    }
    this.datagridHeightCalc();

    this.datatable.columns.adjust();
    if (this.datatable.fixedHeader) {
      this.datatable.fixedHeader.adjust();
    }
    if (this.datatable.responsive) {
      this.datatable.responsive.recalc();
    }
  };

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