import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { TreeComponent } from '../tree/tree.component';
import { QueryService } from '../../services/query.service';
import { Query } from '../../models/query';
import { ExecuteService } from '../../services/execute.service';
import { TableComponent } from '../table/table.component';
import { Result } from '../../models/result';
import { Header } from '../../models/header';
import { Page } from '../../models/page';

@Component({
  selector: 'fbi-result',
  standalone: true,
  imports: [CommonModule, TreeComponent, TableComponent],
  templateUrl: './result.component.html',
  styleUrl: './result.component.scss',
})
export class ResultComponent {
  data: Result = new Result({});

  private query: Query = new Query({});
  private page: Page = new Page({});

  constructor(
    private queryService: QueryService,
    private executeService: ExecuteService
  ) {
    let last: string = '';
    queryService.Query$.subscribe((query: Query) => {
      if (query.isValid()) {
        const current = query.toString();
        if (last !== current) {
          this.query = query;
          this.page = new Page({});
          this.load();
          last = current;
        }
      }
    });
  }

  private load(): void {
    const query = new Query(this.query);
    query.page = new Page(this.page);
    this.executeService.data(query).subscribe((result: Result) => {
      this.data = result;
    });
  }

  onPage(page: Page): void {
    this.page = new Page(page);
    this.load();
  }

  onSort(header: Header): void {
    this.queryService.sort(header.source);
  }
}
