import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ConfigService } from './config.service';
import { BootstrapConfig, LocalizedTextContent, ResolvedStaticPage } from '../../shared/models/config';
import { LanguageService } from '../../services/language.service';
import { ContentPageService } from '../../features/content-management/services/content-page.service';

@Injectable({ providedIn: 'root' })
export class StaticPageResolverService {
  constructor(
    private readonly configService: ConfigService,
    private readonly languageService: LanguageService,
    private readonly contentPageService: ContentPageService
  ) {}

  resolveByKey(key: string, lang?: string): Observable<ResolvedStaticPage | null> {
    return this.configService.loadBootstrap().pipe(
      map(bootstrap => this.resolveByKeyFromBootstrap(bootstrap, key, lang ?? this.languageService.currentLanguage()))
    );
  }

  resolveByRoute(route: string, lang?: string): Observable<ResolvedStaticPage | null> {
    return this.configService.loadBootstrap().pipe(
      map(bootstrap => this.resolveByRouteFromBootstrap(bootstrap, route, lang ?? this.languageService.currentLanguage()))
    );
  }

  resolveByKeyFromBootstrap(bootstrap: BootstrapConfig, key: string, lang: string): ResolvedStaticPage | null {
    return this.contentPageService.resolvePage(bootstrap, key, lang);
  }

  resolveByRouteFromBootstrap(bootstrap: BootstrapConfig, route: string, lang: string): ResolvedStaticPage | null {
    return this.contentPageService.resolvePage(bootstrap, this.normalizeRoute(route).replace(/^\//, ''), lang);
  }

  resolveFooterTitle(groupTitle: string | LocalizedTextContent | undefined, lang: string): string {
    if (!groupTitle) {
      return '';
    }

    if (typeof groupTitle === 'string') {
      return groupTitle;
    }

    return this.resolveLocalizedText(groupTitle, lang, '');
  }

  private resolveLocalizedText(text: LocalizedTextContent | undefined, lang: string, fallback: string): string {
    if (!text) {
      return fallback;
    }

    return text[lang] ?? text['en'] ?? Object.values(text)[0] ?? fallback;
  }

  private normalizeRoute(route: string): string {
    if (!route) {
      return '/';
    }

    return route.startsWith('/') ? route : `/${route}`;
  }
}
