<app-sidebar (scrolledToBottom)="loadMoreLibraries()">
  @if (librariesLoading) {
    <div class="my-10-mx-auto text-center">
      <clr-spinner clrMedium></clr-spinner>
    </div>
  }

  <clr-tree>
    @if (libraries) {
      <clr-tree-node class="search-node">
        <div class="tree-search-wrapper">
          <input
            appStealFocus
            clrInput
            #searchLibTreeInput
            [(ngModel)]="librariesSearch"
            placeholder="Libraries"
            name="input"
            (keyup)="libraryOnFilter()"
            autocomplete="off"
          />
          @if (searchLibTreeInput.value.length < 1) {
            <clr-icon aria-hidden="true" shape="search"></clr-icon>
          }
          @if (searchLibTreeInput.value.length > 0) {
            <clr-icon
              (click)="librariesSearch = ''; libraryOnFilter()"
              aria-label="Clear search"
              shape="times"
            ></clr-icon>
          }
        </div>
      </clr-tree-node>
    }

    @for (library of libraries; track library) {
      @if (!library['hidden'] && library['inForeground']) {
        <clr-tree-node
          (click)="treeNodeClicked($event, library)"
          [(clrExpanded)]="library['expanded']"
          [clrLoading]="library['loadingTables'] && !library.tables"
          [class.clr-expanded]="library['expanded']"
        >
          <p
            (click)="
              lib = library.LIBRARYREF;
              libraryOnClick(library.LIBRARYREF, library)
            "
            class="m-0 cursor-pointer"
          >
            <clr-icon aria-hidden="true" shape="rack-server"></clr-icon>
            {{ library.LIBRARYNAME }}
          </p>
          @if (library['tables']) {
            <clr-tree-node class="search-node">
              <div class="tree-search-wrapper">
                <input
                  appStealFocus
                  clrInput
                  #searchTreeInput
                  [id]="'search_' + library.LIBRARYREF"
                  placeholder="Tables"
                  name="input"
                  [(ngModel)]="library['searchString']"
                  (keyup)="treeOnFilter(library, 'tables')"
                  autocomplete="off"
                />
                @if (searchTreeInput.value.length < 1) {
                  <clr-icon aria-hidden="true" shape="search"></clr-icon>
                }
                @if (searchTreeInput.value.length > 0) {
                  <clr-icon
                    (click)="
                      searchTreeInput.value = '';
                      library['searchString'] = '';
                      treeOnFilter(library, 'tables')
                    "
                    aria-label="Clear search"
                    shape="times"
                  ></clr-icon>
                }
              </div>
            </clr-tree-node>
          }
          @for (
            libTable of library['tables'];
            track libTable;
            let index = $index
          ) {
            <clr-tree-node>
              <clr-tooltip
                *ngVar="
                  index + 1 >
                  licenceState.value.tables_in_library_limit as tableLocked
                "
              >
                @if (libTable.length > 0) {
                  <button
                    clrTooltipTrigger
                    (click)="
                      !tableLocked ? onTableClick(libTable, library) : ''
                    "
                    class="clr-treenode-link"
                    [class.dc-locked-control]="tableLocked"
                    [class.active]="libTabActive(library.LIBRARYREF, libTable)"
                  >
                    @switch (libTable.includes('-FC')) {
                      @case (true) {
                        <clr-icon aria-hidden="true" shape="bolt"></clr-icon>
                      }
                      @case (false) {
                        <clr-icon aria-hidden="true" shape="table"></clr-icon>
                      }
                    }
                    {{ libTable.replace('-FC', '') }}
                  </button>
                }
                @if (tableLocked) {
                  <clr-tooltip-content
                    clrPosition="bottom-right"
                    clrSize="lg"
                    *clrIfOpen
                  >
                    <span>
                      To unlock all tables, contact
                      support&#64;datacontroller.io
                    </span>
                  </clr-tooltip-content>
                }
              </clr-tooltip>
            </clr-tree-node>
          }
        </clr-tree-node>
      }
    }
  </clr-tree>

  @if (librariesPaging) {
    <div class="w-100 text-center">
      <span class="spinner spinner-sm"> Loading... </span>
    </div>
  }
</app-sidebar>

<div class="content-area">
  @if (nullVariables) {
    <div class="modal z-index-highest">
      <div class="modal-dialog" role="dialog" aria-hidden="true">
        <div class="modal-content">
          <div class="modal-header">
            <button aria-label="Close" class="close" type="button">
              <clr-icon aria-hidden="true" shape="close"></clr-icon>
            </button>
            <h3 class="modal-title">Error</h3>
          </div>
          <div class="modal-body">
            <p>You cannot submit empty clauses</p>
          </div>
          <div class="modal-footer">
            <button
              class="btn btn-sm btn-primary"
              (click)="nullVariables = false"
              type="button"
            >
              Ok
            </button>
          </div>
        </div>
      </div>
    </div>
  }

  @if (nullVariables) {
    <div class="modal-backdrop" aria-hidden="true"></div>
  }
  <clr-modal [(clrModalOpen)]="openDownload" [clrModalSize]="'md'">
    <h3 class="modal-title center text-center color-darker-gray">Download</h3>
    <div class="modal-body">
      <div class="clr-col-md-6">
        <clr-select-container class="download-select">
          <label>Please choose download format</label>
          <select [(ngModel)]="downloadFormat" clrSelect>
            <option value="CSV">CSV</option>
            <option value="SAS">Datalines (cards file)</option>
            <option value="PGSQL_DDL">DDL (PGSQL Flavour)</option>
            <option value="SAS_DDL">DDL (SAS Flavour)</option>
            <option value="TSQL_DDL">DDL (TSQL Flavour)</option>
            <option value="EXCEL">Excel (.xlsx)</option>
            <option value="MARKDOWN">Markdown (.md)</option>
          </select>
        </clr-select-container>
      </div>
    </div>
    <div class="modal-footer">
      <button
        type="button"
        class="btn btn-sm btn-outline"
        (click)="openDownload = false"
      >
        Cancel
      </button>
      <button
        [id]="tableTitle"
        type="submit"
        class="btn btn-sm btn-success-outline"
        (click)="
          downloadFormat.includes('DDL') ? downloadDDL() : downloadData()
        "
      >
        Ok
      </button>
    </div>
  </clr-modal>

  <clr-modal [(clrModalOpen)]="webQuery" [clrModalSize]="'lg'">
    <h3 class="modal-title center text-center color-darker-gray">
      Web Query URL
    </h3>
    <div class="modal-body web-query">
      <div class="row">
        <div class="clr-col-lg-12 clr-col-md-12 clr-col-sm-12 clr-col-xs-12">
          <div class="card no-borders">
            <div class="card-header d-flex justify-content-between">
              <span>Copy the below into your preferred client tool:</span>

              <div class="d-block mr-0" class="btn-group">
                <div
                  class="radio btn"
                  (click)="webQueryTab = true; showWebQuery()"
                >
                  <input
                    type="radio"
                    name="btn-group-demo-radios"
                    [checked]="webQueryTab"
                  />
                  <label>TAB</label>
                </div>

                <div
                  class="radio btn"
                  (click)="webQueryTab = false; showWebQuery()"
                >
                  <input
                    type="radio"
                    name="btn-group-demo-radios"
                    [checked]="!webQueryTab"
                  />
                  <label>CSV</label>
                </div>
              </div>
            </div>
            <div class="card-block web-query-wrapper word-break-all">
              <textarea
                clrTextarea
                class="web-query-text"
                rows="4"
                cols="50"
                #cliCommandInput
                (focus)="onCliCommandFocus($event)"
                type="text"
                [value]="webQueryText"
                readonly
              >
              </textarea>
            </div>
            <div class="card-footer">
              <button
                class="btn btn-sm btn-link"
                [ngxClipboard]="cliCommandInput"
                (click)="copyToClip()"
              >
                copy to clipboard
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="modal-footer">
      <button
        type="button"
        class="btn btn-sm btn-outline"
        (click)="webQuery = false"
      >
        close
      </button>
      <!-- <button type="submit" class="btn btn-sm btn-success-outline" (click)="downloadData()">Ok</button> -->
    </div>
  </clr-modal>

  <clr-modal
    [(clrModalOpen)]="filter"
    [clrModalSize]="'xl'"
    [clrModalClosable]="false"
    aria-modal="true"
    class="filter-modal"
  >
    <h3 class="modal-title center text-center color-darker-gray">
      Filter for table:<span> {{ libTab }} </span>
    </h3>
    <div class="modal-body">
      @if (filter) {
        <app-query #queryFilter></app-query>
      }
    </div>
    <div class="modal-footer">
      <button (click)="resetFilter()" type="button" class="btn btn-sm btn-link">
        reset filter
      </button>
      <button
        type="button"
        class="btn btn-outline btn-sm"
        (click)="filter = false; removeQuery()"
      >
        Cancel
      </button>
      <button
        [clrLoading]="submitLoading"
        type="submit"
        class="btn btn-sm btn-success-outline"
        (click)="sendClause()"
      >
        Ok
      </button>
    </div>
  </clr-modal>

  <clr-modal [(clrModalOpen)]="queryErr">
    <h3 class="modal-title">Error</h3>
    <div class="modal-body">
      <p>{{ queryErrMessage }}</p>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-outline" (click)="queryErr = false">
        Cancel
      </button>
      <button type="button" class="btn btn-primary" (click)="queryErr = false">
        Ok
      </button>
    </div>
  </clr-modal>

  @if (loadingTableView) {
    <div class="loadingSpinner">
      <span class="spinner"> Loading... </span>
      <div class="mt-10">
        <p cds-text="section">Loading Table Viewer</p>
      </div>
    </div>
  }

  @if (!loadingTableView) {
    <div class="card no-borders h-100 d-flex clr-flex-column">
      @if (table) {
        <div
          class="header-row clr-row justify-content-between clr-justify-content-center w-100 m-0"
        >
          <section class="form-block table-search-wrapper sw clr-col-md">
            <form class="d-flex align-items-center" clrForm>
              <div class="input-wrapper">
                <input
                  #searchEl
                  (keyup.enter)="searchTable(searchEl)"
                  clrInput
                  [type]="searchNumeric ? 'number' : 'text'"
                  placeholder="Search"
                  name="search-input"
                />
                @if (!searchLoading) {
                  <clr-icon
                    (click)="searchTable(searchEl)"
                    aria-label="Search"
                    shape="search"
                  ></clr-icon>
                }
                @if (searchLoading) {
                  <span class="spinner spinner-inline"> Loading... </span>
                }
              </div>
              <clr-checkbox-container>
                <clr-checkbox-wrapper>
                  <input
                    type="checkbox"
                    clrCheckbox
                    [(ngModel)]="searchNumeric"
                    name="numeric_check"
                  />
                  <label>Numeric</label>
                </clr-checkbox-wrapper>
              </clr-checkbox-container>
            </form>
          </section>
          <div class="title-col clr-col-auto clr-flex-column clr-flex-sm-row">
            <p
              cds-text="section"
              class="clr-flex-column d-flex clr-flex-sm-row clr-align-items-center clr-justify-content-center"
            >
              <clr-tooltip class="d-flex clr-align-items-center">
                <clr-icon
                  clrTooltipTrigger
                  (click)="datasetInfo = true"
                  aria-label="View dataset meta info"
                  shape="info-circle"
                  class="is-highlight cursor-pointer"
                  size="24"
                ></clr-icon>
                @if (tableTitle?.includes('-FC')) {
                  <clr-icon
                    aria-hidden="true"
                    shape="bolt"
                    class="color-yellow mr-5"
                  ></clr-icon>
                }
                @if (tableTitle && tableTitle.length > 0) {
                  <span clrTooltipTrigger>
                    {{ tableTitle?.replace('-FC', '') }}
                  </span>
                }
                @if (this.dsNote && this.dsNote.length > 0) {
                  <clr-tooltip-content
                    clrPosition="bottom-left"
                    clrSize="lg"
                    *clrIfOpen
                  >
                    {{ this.dsNote }}
                  </clr-tooltip-content>
                }
              </clr-tooltip>
              @if (tableTitle && tableTitle.length > 0) {
                @if (numberOfRows !== null) {
                  <span>
                    ({{ numberOfRows | thousandSeparator: ',' }}
                    {{ numberOfRows! === 1 ? 'row' : 'rows' }},
                    {{ filterCols.length
                    }}{{ filterCols.length === 1 ? ' col' : ' cols' }})
                  </span>
                }
                <clr-icon
                  (click)="reloadTableData()"
                  aria-label="Reload data"
                  class="refresh-table"
                  shape="refresh"
                ></clr-icon>
              }
            </p>
          </div>
          <div class="options-col clr-col-md">
            @if (tableTitle && !abortActive) {
              <clr-dropdown
                class="options-dropdown"
                [clrCloseMenuOnItemClick]="true"
              >
                <button
                  type="button"
                  class="btn btn-sm btn-outline filterSide"
                  clrDropdownTrigger
                >
                  <clr-icon aria-hidden="true" shape="cog" size="15"></clr-icon>
                  options
                </button>
                <clr-dropdown-menu clrPosition="bottom-right" *clrIfOpen>
                  <div (click)="newViewbox()" clrDropdownItem>
                    <clr-icon aria-hidden="true" shape="view-cards"></clr-icon>
                    <span>Viewboxes</span>
                  </div>
                  @if (tableEditExists()) {
                    <div (click)="editTable()" clrDropdownItem>
                      <clr-icon aria-hidden="true" shape="pencil"></clr-icon>
                      <span>Edit</span>
                    </div>
                  }
                  @if (tableuri) {
                    <div (click)="goToLineage()" clrDropdownItem>
                      <clr-icon aria-hidden="true" shape="switch"></clr-icon>
                      <span>Lineage</span>
                    </div>
                  }
                  <div (click)="openQb()" clrDropdownItem>
                    <clr-icon aria-hidden="true" shape="filter"></clr-icon>
                    <span>Filter</span>
                  </div>
                  <div (click)="openDownload = true" clrDropdownItem>
                    <clr-icon aria-hidden="true" shape="download"></clr-icon>
                    <span>Download</span>
                  </div>
                  <div (click)="showWebQuery()" clrDropdownItem>
                    <clr-icon
                      aria-hidden="true"
                      shape="download-cloud"
                    ></clr-icon>
                    <span>Web Query URL</span>
                  </div>
                </clr-dropdown-menu>
              </clr-dropdown>
            }
          </div>
          @if (
            queryText !== '1=1' &&
            !['', ' '].includes(queryText) &&
            !abortActive
          ) {
            <div class="clr-col-md-12 infoBar">
              <span
                >FILTER : <b>{{ queryText }}</b></span
              >
            </div>
          }
        </div>
      }
      @if (!lib && !table && !noDataReqErr && !noData) {
        <div class="no-table-selected">
          <img
            src="images/select-library.png"
            class="select-table-icon"
            alt="select a library icon"
          />
          <h3 class="text-center color-gray mt-10" cds-text="section">
            Please select a library
          </h3>
        </div>
      }
      @if (!noData && !noDataReqErr && !table && lib) {
        <div
          class="header-row clr-row border-bottom-divider justify-content-between w-100 m-0"
        >
          <section
            class="form-block table-search-wrapper sw clr-col-md"
          ></section>
          <div class="title-col clr-col-auto mt-15 mb-15">
            <p cds-text="section">
              {{ lib }}
            </p>
            <clr-icon
              (click)="reloadLibInfo()"
              aria-label="Reload library info"
              class="refresh-table"
              shape="refresh"
            ></clr-icon>
          </div>
          <div class="options-col clr-col-md"></div>
        </div>
        <div class="text-center mt-10">
          @if (libinfo === null) {
            <clr-spinner clrMedium></clr-spinner>
          }
        </div>
        @if (libinfo !== null) {
          <div class="no-table-selected-info pointer-events-none">
            <img
              src="images/select-table.png"
              class="select-table-icon"
              alt="select table icon"
            />
            <p class="text-center color-gray mt-10" cds-text="section">
              Please select a table
            </p>
          </div>
        }
        @if (libinfo !== null) {
          <div class="libinfo m-0 clr-row">
            @if (libinfo.length < 1) {
              <p class="text-center m-0 w-100">
                No library info found. Click
                <clr-icon
                  (click)="reloadLibInfo()"
                  aria-label="Reload library info"
                  class="refresh-table m-0"
                  shape="refresh"
                ></clr-icon>
                button to refresh.
              </p>
            }
            @if (libinfo.length > 0) {
              <table>
                @if (libinfo[0].ENGINE !== '') {
                  <tr>
                    <td class="m-0">ENGINE:</td>
                    <td class="m-0 font-bold">
                      {{ libinfo[0] ? libinfo[0].ENGINE : '' }}
                    </td>
                  </tr>
                }
                @if (libinfo[0].LIBID !== '') {
                  <tr>
                    <td class="m-0">LIBID:</td>
                    <td class="m-0 font-bold">
                      {{ libinfo[0] ? libinfo[0].LIBID : '' }}
                    </td>
                  </tr>
                }
                @if (libinfo[0].LIBNAME !== '') {
                  <tr>
                    <td class="m-0">LIBNAME:</td>
                    <td class="m-0 font-bold">
                      {{ libinfo[0] ? libinfo[0].LIBNAME : '' }}
                    </td>
                  </tr>
                }
                @if (libinfo[0].LIBSIZE !== null) {
                  <tr>
                    <td class="m-0">LIBSIZE:</td>
                    <td class="m-0 font-bold">
                      {{ libinfo[0] ? (libinfo[0].LIBSIZE | convertSize) : '' }}
                    </td>
                  </tr>
                }
                @if (libinfo[0].OWNERS !== '') {
                  <tr>
                    <td class="m-0">OWNERS:</td>
                    <td class="m-0 font-bold">
                      {{ libinfo[0] ? libinfo[0].OWNERS : '' }}
                    </td>
                  </tr>
                }
                @if (libinfo[0].PATHS !== '') {
                  <tr>
                    <td class="m-0">PATHS:</td>
                    <td class="m-0 font-bold">
                      {{ libinfo[0] ? libinfo[0].PATHS : '' }}
                    </td>
                  </tr>
                }
                @if (libinfo[0].PERMS !== '') {
                  <tr>
                    <td class="m-0">PERMS:</td>
                    <td class="m-0 font-bold">
                      {{ libinfo[0] ? libinfo[0].PERMS : '' }}
                    </td>
                  </tr>
                }
                @if (libinfo[0].SCHEMAS !== '') {
                  <tr>
                    <td class="m-0">SCHEMAS:</td>
                    <td class="m-0 font-bold">
                      {{ libinfo[0] ? libinfo[0].SCHEMAS : '' }}
                    </td>
                  </tr>
                }
                @if (libinfo[0].TABLE_CNT !== null) {
                  <tr>
                    <td class="m-0">TABLE_CNT:</td>
                    <td class="m-0 font-bold">
                      {{ libinfo[0] ? libinfo[0].TABLE_CNT : '' }}
                    </td>
                  </tr>
                }
                @if (libinfo[0].CATALOG_CNT !== null) {
                  <tr>
                    <td class="m-0">CATALOG_CNT:</td>
                    <td class="m-0 font-bold">
                      {{ libinfo[0] ? libinfo[0].CATALOG_CNT : '' }}
                    </td>
                  </tr>
                }
              </table>
            }
          </div>
        }
      }
      @if (noData || noDataReqErr) {
        <div class="card-block noData">
          <clr-icon
            aria-hidden="true"
            shape="warning-standard"
            size="60"
            class="is-info"
          ></clr-icon>
          @if (noData) {
            <h3 class="text-center color-gray">
              No data found with given conditions
            </h3>
          }
          @if (noDataReqErr) {
            <h3 class="text-center color-gray">
              No data found due to sas request error
            </h3>
          }
        </div>
      }
      @if (!noData && !noDataReqErr && table) {
        <div class="clr-flex-1">
          <div class="hot-wrapper clr-flex-1">
            <hot-table
              #hotInstance
              id="hotTable"
              class="view-hot"
              [data]="hotTable.data"
              [settings]="hotTableSettings"
            >
            </hot-table>
          </div>
        </div>
      }
      <div>
        @if (
          licenceState.value.viewer_rows_allowed !== Infinity &&
          hotTable.data &&
          hotTable.data.length > licenceState.value.viewer_rows_allowed
        ) {
          <p class="mt-2-i w-100 text-center">
            To display more than
            {{ licenceState.value.viewer_rows_allowed }} rows, contact
            <contact-link />
          </p>
        }
      </div>
    </div>
  }
</div>

<app-dataset-info
  [(open)]="datasetInfo"
  [dsmeta]="dsmeta"
  [versions]="versions"
  (rowClicked)="datasetInfoModalRowClicked($event)"
>
</app-dataset-info>

<app-viewboxes [(viewboxModal)]="viewboxOpen"></app-viewboxes>
