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 { forkJoin } from 'rxjs';
import { Header } from '../../models/header';
import { TableComponent } from '../table/table.component';

@Component({
  selector: 'fbi-result',
  standalone: true,
  imports: [CommonModule, TreeComponent, TableComponent],
  templateUrl: './result.component.html',
  styleUrl: './result.component.scss',
})
export class ResultComponent {
  headers: Header[] = [];
  rows: Record<string, any>[] = [];

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

  private load(query: Query): void {
    forkJoin({
      headers: this.executeService.headers(query),
      data: this.executeService.data(query),
    }).subscribe(
      (result: { headers: Header[]; data: Record<string, any>[] }) => {
        this.headers = result.headers;
        this.rows = result.data;
      }
    );
  }
}
