/*
 * Copyright (C) 2018 Robert Bosch GmbH Copyright (C) 2018 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { Location } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Inject, Injectable } from '@angular/core';

import { Observable, throwError } from 'rxjs';
import { map } from 'rxjs/operators';
import { CoreConfig } from '../core-configuration/core-config';
import { CORE_CONFIG } from '../core-configuration/core-config.token';
import { BciImprintComponent } from '../imprint/bci-imprint.component';
import { BciImprintIntl } from '../imprint/imprint-intl';
import { SidebarNavItem } from '../layout';
import { ModalWindowService } from '../modal-window/modal-window.service';
import { NavigationResponse } from './NavigationResponse';

@Injectable({
  providedIn: 'root',
})
export class NavigationService {
  sidebarLinks: SidebarNavItem[] = [];

  constructor(
    public imprintIntl: BciImprintIntl,
    private modalWindowService: ModalWindowService,
    private http: HttpClient,
    private location: Location,
    @Inject(CORE_CONFIG) private config: CoreConfig
  ) {}

  getNavigationItems(): Observable<SidebarNavItem[]> {
    if (this.config && this.config.endpointNavigation) {
      const normalizedUrl = this.location.prepareExternalUrl(this.config.endpointNavigation);

      return this.http.get(normalizedUrl).pipe(
        map((links: NavigationResponse) => {
          if (links instanceof Array) {
            this.sidebarLinks = links;
          } else {
            this.sidebarLinks = links.results;
          }
          return this.sidebarLinks;
        })
      );
    } else {
      return throwError('NavigationService: no endpointNavigation provided in CORE_CONFIG');
    }
  }

  getImprintSidebarLink() {
    return {
      id: 'imprint',
      title: this.imprintIntl.title,
      icon: 'Bosch-Ic-information',
      cb: () =>
        this.modalWindowService.openDialogWithComponent(BciImprintComponent, {
          width: '800px',
        }),
    };
  }
}
