import { Injectable } from "@angular/core";
import { Title } from "@angular/platform-browser";
import { TranslateService } from "@ngx-translate/core";
import { newsObserver } from "src/app/components/resources-sidebar/resources-sidebar.component";

@Injectable({
  providedIn: "root",
})
export class TitleService {
  titlePart: string = "Clarabot Nano";
  news: number = 0;
  currentTabTitle: string;

  constructor(private title: Title, private translate: TranslateService) {
    this.translate.onLangChange.subscribe(() =>
      this.setTabTitle(this.currentTabTitle)
    );

    newsObserver.subscribe((news) => {
      this.news = news;
      this.setTabTitle(this.currentTabTitle);
    });
  }

  setTabTitle(tabTitle: string): void {
    if (!tabTitle) return;

    this.currentTabTitle = tabTitle;

    this.translate.get(tabTitle).subscribe((translatedTabTitle) => {
      this.title.setTitle(this.constructTitle(translatedTabTitle));
    });
  }

  constructTitle(tabTitle: string): string {
    let newsInTitle = this.news == 0 ? "" : "(" + this.news + ") ";
    return `${newsInTitle}${tabTitle} - ${this.titlePart}`;
  }
}
