/*
 * Copyright (C) 2023 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

import {Component} from '@angular/core';
import {NavigationEnd, Router} from '@angular/router';
import {
  SCAppConfigurationMenuCategory,
  SCLanguage,
  SCThingTranslator,
  SCTranslations,
} from '@openstapps/core';
import {ConfigProvider} from '../../config/config.provider';
import {LangChangeEvent, TranslateService} from '@ngx-translate/core';
import {NGXLogger} from 'ngx-logger';

@Component({
  selector: 'stapps-navigation-tabs',
  templateUrl: 'tabs.template.html',
  styleUrls: ['./tabs.component.scss'],
})
export class TabsComponent {
  /**
   * Possible languages to be used for translation
   */
  language: keyof SCTranslations<SCLanguage>;

  /**
   * Menu entries from config module
   */
  menu: SCAppConfigurationMenuCategory[];

  /**
   * Core translator
   */
  translator: SCThingTranslator;

  /**
   * Name of selected tab
   */
  selectedTab: string;

  constructor(
    private readonly configProvider: ConfigProvider,
    public translateService: TranslateService,
    private readonly logger: NGXLogger,
    private readonly router: Router,
  ) {
    this.language = this.translateService.currentLang as keyof SCTranslations<SCLanguage>;
    this.translator = new SCThingTranslator(this.language);
    void this.loadMenuEntries();
    this.router.events.subscribe((event: unknown) => {
      if (event instanceof NavigationEnd) {
        setTimeout(() => {
          this.selectTab(event.url);
        }, 300);
      }
    });
    this.selectTab(router.url);

    translateService.onLangChange?.subscribe((event: LangChangeEvent) => {
      this.language = event.lang as keyof SCTranslations<SCLanguage>;
      this.translator = new SCThingTranslator(this.language);
    });
  }

  /**
   * Loads menu entries from configProvider
   */
  async loadMenuEntries() {
    try {
      const menus = (await this.configProvider.getValue('menus')) as SCAppConfigurationMenuCategory[];

      const menu = menus.slice(0, 5);
      if (menu) {
        this.menu = menu;
      }
    } catch (error) {
      this.logger.error(`error from loading menu entries: ${error}`);
    }
  }

  /* eslint-disable @typescript-eslint/no-explicit-any */
  selectTab(url: string) {
    if (!this.menu) {
      return;
    }
    if (url === '/') {
      this.selectedTab = (this.menu[0] as any)?.title ?? '';
      return;
    }
    const candidate = this.menu.slice(0, 5).find(category => url.includes(category.route));
    this.selectedTab = candidate?.title ?? '';
  }
}
