import {Component} from '@angular/core';
import {ActivatedRoute, NavigationEnd, NavigationStart, Params, Router} from '@angular/router';

import {EnvProperties} from './openaireLibrary/utils/properties/env-properties';
import {MenuItem, RootMenuItem} from './openaireLibrary/sharedComponents/menu';
import {EnvironmentSpecificService} from './openaireLibrary/utils/properties/environment-specific.service';
import {Session, User} from './openaireLibrary/login/utils/helper.class';
import {HelperFunctions} from "./openaireLibrary/utils/HelperFunctions.class";
import {UserManagementService} from "./openaireLibrary/services/user-management.service";
import {properties} from "../environments/environment";
import {BehaviorSubject, Subscriber} from "rxjs";
import {StakeholderService} from "./openaireLibrary/monitor/services/stakeholder.service";
import {Header} from "./openaireLibrary/sharedComponents/navigationBar.component";
import {SmoothScroll} from "./openaireLibrary/utils/smooth-scroll";

@Component({
  selector: 'app-root',
  template: `
    <div class="monitorApp">
      <navbar *ngIf="properties && showMenu && header" portal="monitor" [header]="header" [onlyTop]="false"
              [userMenuItems]=userMenuItems [menuItems]=menuItems [user]="user"
              [showMenu]=showMenu [properties]="properties"></navbar>
      <schema2jsonld *ngIf="properties " [URL]="properties.domain + properties.baseLink"
                     [logoURL]="properties.domain + properties.baseLink+'/assets/common-assets/logo-small-monitor.png'"
                     type="home" 
                     description="OpenAIRE - Monitor, A new era of monitoring research. Open data. Open methodologies. Work together with us to view, understand and visualize research statistics and indicators. "
                     name="OpenAIRE Monitor" [searchAction]="true" [searchActionRoute]="properties.domain + properties.baseLink + '/browse'">
      </schema2jsonld>
      <div class="custom-main-content">
        <main>
          <router-outlet></router-outlet>
        </main>
      </div>
      <cookie-law position="bottom">
        OpenAIRE uses cookies in order to function properly.<br>
        Cookies are small pieces of data that websites store in your browser to allow us to give you the best browsing
        experience possible.
        By using the OpenAIRE portal you accept our use of cookies. <a
          href="https://www.openaire.eu/privacy-policy#cookies" target="_blank"> Read more <span class="uk-icon">
            <svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" icon="chevron-right"
                 ratio="1"><polyline fill="none" stroke="#000" stroke-width="1.03"
                                     points="7 4 13 10 7 16"></polyline></svg>
            </span></a>
      </cookie-law>
      <bottom *ngIf="properties && showMenu" [grantAdvance]="false"
              [properties]="properties"></bottom>
    </div>
  `
  
})
export class AppComponent {
  userMenuItems: MenuItem[] = [];
  menuItems: RootMenuItem [] = [];
  bottomMenuItems: MenuItem[] = [];
  properties: EnvProperties = properties;
  showMenu: boolean = false;
  user: User;
  params: BehaviorSubject<Params> = new BehaviorSubject<Params>(null);
  url: string;
  header: Header;
  logoPath: string = 'assets/common-assets/';
  private subscriptions: any[] = [];
  
  constructor(private  route: ActivatedRoute, private propertiesService: EnvironmentSpecificService,
              private router: Router, private stakeholderService: StakeholderService, private smoothScroll: SmoothScroll,
              private userManagementService: UserManagementService) {
    this.subscriptions.push(router.events.forEach((event) => {
    if (event instanceof NavigationEnd) {
        this.url = event.url;
        let r = this.route;
        while (r.firstChild) {
          r = r.firstChild;
        }
        let params = r.snapshot.params;
        this.params.next(params);
      }
    }));
  }
  
  ngOnInit() {
    this.subscriptions.push(this.userManagementService.getUserInfo().subscribe(user => {
      this.user = user;
      this.setUserMenu();
      this.header = {
        route: "/",
        url: null,
        title: 'monitor',
        logoUrl: this.logoPath + 'logo-large-monitor.png',
        logoSmallUrl:this.logoPath + 'logo-small-monitor.png',
        position:'left',
        badge:true
      };
      this.buildMenu();
    }));
  }
  
  public ngOnDestroy() {
    this.subscriptions.forEach(value => {
      if (value instanceof Subscriber) {
        value.unsubscribe();
      }
    });
    this.userManagementService.clearSubscriptions();
    this.stakeholderService.clearSubscriptions();
    this.smoothScroll.clearSubscriptions();
  }
  
  public buildMenu() {
    this.menuItems = [];
    this.menuItems.push({
      rootItem: new MenuItem("about", "About", "", "/about/learn-how", false, [], null, {}),
      items: []
    });
    this.menuItems.push({
      rootItem: new MenuItem("stakeholders", "Browse", "", "browse", false, [], null, {}),
      items: []
    });
    this.menuItems.push({
      rootItem: new MenuItem("contact-us", "Contact us", "", "/contact-us", false, [], null, {}),
      items: []
    });
    this.bottomMenuItems = [
      new MenuItem("", "About", "https://beta.openaire.eu/project-factsheets", "", false, [], [], {}),
      new MenuItem("", "News - Events", "https://beta.openaire.eu/news-events", "", false, [], [], {}),
      new MenuItem("", "Blog", "https://blogs.openaire.eu/", "", false, [], [], {}),
      new MenuItem("", "Contact us", "https://beta.openaire.eu/contact-us", "", false, [], [], {})
    ];
    this.showMenu = true;
  }
  
  public setUserMenu() {
    this.userMenuItems = [];
    if (this.user) {
      if (Session.isPortalAdministrator(this.user) || Session.isMonitorCurator(this.user) || Session.isKindOfMonitorManager(this.user)) {
        this.userMenuItems.push(new MenuItem("", "Manage profiles",
          this.properties.domain + properties.baseLink + "/dashboard/admin", "", false, [], [], {}))
      }
      this.userMenuItems.push(new MenuItem("", "User information", "", "/user-info", false, [], [], {}));
    }
  }
}
