import {
  Component,
  ElementRef,
  HostListener,
  OnDestroy,
  OnInit,
} from "@angular/core";
import { RouterHandler } from "../../../shared/services/router-handler.service";
import { SearchService } from "../../../shared/server-services/search-service";

@Component({
  selector: "app-search-input",
  templateUrl: "./search-input.component.html",
  styleUrls: ["./search-input.component.scss"],
})
export class SearchInputComponent implements OnInit, OnDestroy {
  public resourceId; // opened resource read from url (chat or drive)
  public searchStarted = false;
  public search: string = "";
  public all: string = SearchService.QUERY_ALL; // only way to inject this into the DOM

  private onRouteChangeSearch = (res) => {
    this.search = res.fragment?.search;
    this.resourceId = res.params.resourceId;
  };

  private onRouteChangeResource = (res) => {
    this.resourceId = res.params.id;
  };

  constructor(
    private eRef: ElementRef,
    private routerHandler: RouterHandler,
    private searchService: SearchService
  ) {
    routerHandler.subscribe("search", this.onRouteChangeSearch);
    routerHandler.subscribe("room", this.onRouteChangeResource);

    if (
      this.routerHandler.isOnPage("room") ||
      this.routerHandler.isOnPage("search")
    ) {
      this.onRouteChangeResource(this.routerHandler.getRoute());
    }

    /*if (this.routerHandler.isOnPage("search")) {
      this.search = this.routerHandler.getRoute().fragment?.search;
      this.doSearch(this.search)
    }*/
  }

  ngOnInit(): void {}

  ngOnDestroy() {
    this.routerHandler.unsubscribe("search", this.onRouteChangeSearch);
    this.routerHandler.unsubscribe("room", this.onRouteChangeResource);
  }

  @HostListener("document:click", ["$event"]) clickout(event) {
    if (this.searchStarted) {
      if (!this.eRef.nativeElement.contains(event.target)) {
        // clicked outside
        this.searchStarted = false;
      }
    }
  }

  public onSearch(event, search) {
    //if (search.length > 2){
    if (event.key == "Enter") {
      this.doSearch(search);
    } else {
      this.searchStarted = true;
    }
    /*}
    else{
      this.searchStarted = false;
    }*/
  }

  public doSearch(search, globally = false) {
    this.searchStarted = false;

    let fragment = this.routerHandler.getRoute().fragment;
    fragment["search"] = search;

    this.searchService.search(
      globally || !this.resourceId ? SearchService.QUERY_ALL : this.resourceId,
      search,
      "en"
    ); // TODO lang

    this.routerHandler.navigate(
      [
        "/search/",
        globally || !this.resourceId
          ? SearchService.QUERY_ALL
          : this.resourceId,
      ],
      { fragment: this.routerHandler.fragmentToRaw(fragment) }
    );
  }
}
