import { Component, Input, OnDestroy, OnInit } from "@angular/core";
import { RouterHandler } from "../../../shared/services/router-handler.service";
import { SearchResult } from "../../../shared/server-services/search-service";
import { sideMenuActiveObserver } from "../../header/header.component";

@Component({
  selector: "app-search-sidebar-view",
  templateUrl: "./search-sidebar-view.component.html",
  styleUrls: ["./search-sidebar-view.component.scss"],
})
export class SearchSidebarViewComponent implements OnInit, OnDestroy {
  @Input("result") data: Map<string, SearchResult[]>;
  @Input("search") searchQuery: string;
  @Input("resourceId") searchResourceId: string;

  public activeResourceId; // clicked, to check the drive
  public isOnSearchPage = false;

  public onRouterChangeSearch = (res) => {
    this.isOnSearchPage = true;
    this.searchQuery = res.fragment;
    this.searchResourceId = res.params.resourceId;
  };

  public onRouterChangeResource = (res) => {
    this.isOnSearchPage = false;
    this.activeResourceId = res.params.id;
  };

  constructor(private routerHandler: RouterHandler) {
    this.routerHandler.subscribe("search", this.onRouterChangeSearch);
    this.routerHandler.subscribe("res", this.onRouterChangeResource);
  }

  ngOnInit(): void {}

  ngOnDestroy() {
    this.routerHandler.unsubscribe("search", this.onRouterChangeSearch);
    this.routerHandler.unsubscribe("res", this.onRouterChangeResource);
  }

  public openDrive(resourceId) {
    sideMenuActiveObserver.next(false);
    if (this.data.has(resourceId)) {
      this.routerHandler.navigate(["/room/", resourceId, "drive"]);
    }
  }

  public openPath(resourceId, result: SearchResult) {
    sideMenuActiveObserver.next(false);
    let fragment = this.routerHandler.getRoute().fragment;
    fragment["path"] = result.dir;
    fragment["file"] = result.file.fullName;
    this.routerHandler.navigate(["/room/", resourceId, "drive"], {
      fragment: this.routerHandler.fragmentToRaw(fragment),
    });
  }

  public openAllResult() {
    this.routerHandler.navigate(["/search/", this.searchResourceId], {
      fragment: this.searchQuery,
    });
  }
}
