import { Component, OnDestroy, OnInit } from '@angular/core';
import { RoomService } from 'src/app/shared/server-services/room.service';
import { SearchResult, SearchService } from 'src/app/shared/server-services/search-service';
import { RouterHandler } from 'src/app/shared/services/router-handler.service';

@Component({
  selector: 'app-search-view',
  templateUrl: './search-view.component.html',
  styleUrls: ['./search-view.component.scss']
})
export class SearchViewComponent implements OnInit, OnDestroy {

  public query;
  public searchResults: SearchResult[];
  public resourceId;

  public searchHandler(resourceId, query, results){
    this.searchResults = this.searchService.getResults();
  }

  public onRouteChange(res){
    this.searchResults = this.searchService.getResults();
  }

  constructor(
    private searchService: SearchService,
    private routerHandler: RouterHandler,
    private roomService: RoomService
    ) {

      this.routerHandler.subscribe('search', this.onRouteChange.bind(this));
      if (this.routerHandler.isOnPage("search")){
        /*setTimeout(()=>{
          // need to get it async, because of the search input should trigger the search first
          this.searchResults = this.searchService.getResults();
        }, 1)*/
        this.onRouteChange(this.routerHandler.getRoute())
      }

      this.searchService.subscribe(this.searchHandler.bind(this));
      this.searchResults = this.searchService.getResults();
    }

  ngOnInit(): void {

  }

  ngOnDestroy(){
    this.searchService.unsubscribe(this.searchHandler.bind(this));
    this.routerHandler.unsubscribe('search', this.onRouteChange.bind(this));
  }

}
