import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { MatSortModule } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
import { Layer, LayerType } from 'src/app/models/layer.model';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { Router, RouterLink } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatSelectModule } from '@angular/material/select';
import { FormsModule } from '@angular/forms';
import { MatChipsModule} from '@angular/material/chips';
import { MatIconModule } from '@angular/material/icon';
import { KeyValuePipe, NgFor } from '@angular/common';
import { ScrollEndDirective } from 'src/app/directives/scroll-end.directive';
import { Subject, debounceTime, distinctUntilChanged } from 'rxjs';

@Component({
    selector: 'diunabi-layers-list',
    templateUrl: './layers-list.component.html',
    styleUrls: ['./layers-list.component.scss'],
    standalone: true,
    imports: [MatGridListModule, MatButtonModule, RouterLink, MatFormFieldModule, 
      MatInputModule, MatTableModule, MatSortModule, MatSelectModule, FormsModule,
      MatChipsModule, MatIconModule, NgFor, ScrollEndDirective, KeyValuePipe]
})
export class LayersListComponent implements OnInit {
  displayedColumns = ['number', 'name', 'type'];
  dataSource!: Layer[];
  LayerType = LayerType;

  start = 0;
  limit = 50;
  end: number = this.limit + this.start;
  loadingInProgress = false;

  type: LayerType | '' = '';
  name: string = '';
  nameUpdate = new Subject<string>();

  constructor(
    private _http: HttpClient,
    private _router: Router
  ) { }

  async ngOnInit() {
    this.nameUpdate.pipe(
      debounceTime(400),
      distinctUntilChanged())
      .subscribe(() => {
        this.loadList();
      });
      await this.loadList();
  }

  async loadList() {
    this.start = 0;
    this.end = this.limit;
    this.dataSource = await Layer.getList(this._http, this.start, this.limit, this.name, this.type);
  }
 
  async loadMore() {
    this.start = this.end;
    this.end += this.limit;
    this.dataSource = this.dataSource.concat(
      await Layer.getList(this._http, this.start, this.limit, this.name, this.type)
      );
  }

  openInNewTab(element: Layer) {
    const url = this._router.serializeUrl(
      this._router.createUrlTree([`/app/layers/Detail/${element.id}`])
    );
    window.open(url, '_blank');
  }
}

