import {ChangeDetectorRef, Component, OnDestroy, OnInit} from '@angular/core';
import {ActivatedRoute, NavigationEnd, Params, Router} from '@angular/router';
import {EnvProperties} from './openaireLibrary/utils/properties/env-properties';
import {EnvironmentSpecificService} from './openaireLibrary/utils/properties/environment-specific.service';
import {Session, User} from './openaireLibrary/login/utils/helper.class';
import {UserManagementService} from "./openaireLibrary/services/user-management.service";
import {StakeholderService} from "./openaireLibrary/monitor/services/stakeholder.service";
import {BehaviorSubject, Subscriber} from "rxjs";
import {LayoutService} from "./openaireLibrary/dashboard/sharedComponents/sidebar/layout.service";
import {MenuItem, RootMenuItem} from "./openaireLibrary/sharedComponents/menu";
import {Stakeholder, Topic} from "./openaireLibrary/monitor/entities/stakeholder";
import {LinksResolver} from "./search/links-resolver";
import {Header} from "./openaireLibrary/sharedComponents/navigationBar.component";


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit, OnDestroy {
  properties: EnvProperties;
  user: User;
  params: BehaviorSubject<Params> = new BehaviorSubject<Params>(null);
  hasSidebar: boolean = false;
  hasHeader: boolean = false;
  hasAdminMenu: boolean = false;
  hasMiniMenu: boolean = false;
  isFrontPage: boolean = false;
  isViewPublic: boolean = false;
  sideBarItems: MenuItem[] = [];
  specialSideBarMenuItem:MenuItem = null;
  menuItems: RootMenuItem[] = [];
  menuHeader: Header =  { route: "/", url: null, title: "Default menu header", logoUrl: null, logoSmallUrl:null, position:'center', badge: false };
  userMenuItems: MenuItem[] = [new MenuItem("", "My profile", "", "", false, [], [], {})];
  adminMenuItems: MenuItem[] = [];
  stakeholder: Stakeholder = null;
  activeTopic: Topic = null;
  innerWidth;
  private subscriptions: any[] = [];
  
  constructor(private route: ActivatedRoute,
              private propertiesService: EnvironmentSpecificService,
              private router: Router,
              private userManagementService: UserManagementService,
              private layoutService: LayoutService,
              private stakeholderService: StakeholderService,
              private cdr: ChangeDetectorRef) {
    this.subscriptions.push(this.router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        let r = this.route;
        while (r.firstChild) {
          r = r.firstChild;
        }
        let params = r.snapshot.params;
        this.params.next(params);
      }
    }));
  }
  
  ngOnInit() {
    if(window) {
      this.innerWidth = window.innerWidth;
    }
    this.subscriptions.push(this.layoutService.hasSidebar.subscribe(hasSidebar => {
      this.hasSidebar = hasSidebar;
      if (this.hasSidebar === false) {
        this.layoutService.setOpen(false);
      }
      this.cdr.detectChanges();
    }));
    this.subscriptions.push(this.layoutService.hasHeader.subscribe(hasHeader => {
      this.hasHeader = hasHeader;
      this.cdr.detectChanges();
    }));
    this.subscriptions.push(this.layoutService.hasAdminMenu.subscribe(hasAdminMenu => {
      this.hasAdminMenu = hasAdminMenu;
      this.cdr.detectChanges();
    }));
    this.subscriptions.push(this.layoutService.hasMiniMenu.subscribe(hasMiniMenu => {
      this.hasMiniMenu = hasMiniMenu;
      this.cdr.detectChanges();
    }));
    this.subscriptions.push(this.layoutService.isFrontPage.subscribe(isFrontPage => {
      this.isFrontPage = isFrontPage;
      this.cdr.detectChanges();
    }));
    this.route.queryParams.subscribe(params => {
      this.isViewPublic = (params['view'] == 'public');
    });
    this.layoutService.setOpen(false);
    this.propertiesService.loadEnvironment()
      .then(properties => {
        this.properties = properties;
        this.subscriptions.push(this.params.subscribe(params => {
          let isSearch = this.router.url.includes('search');
          if (params && params['stakeholder']) {
            if (!this.stakeholderService.stakeholder ||
              this.stakeholderService.stakeholder.alias !== params['stakeholder']) {
              this.stakeholderService.getStakeholder(this.properties.monitorServiceAPIURL, params['stakeholder']).subscribe(stakeholder => {
                if(stakeholder) {
                  this.stakeholder = stakeholder;
                  this.buildMenu();
                  LinksResolver.setProperties(this.stakeholder.alias);
                  this.stakeholderService.setStakeholder(stakeholder);
                  this.layoutService.setSmallScreen((this.innerWidth && this.innerWidth < 1219));
                  this.layoutService.setOpen(!(this.innerWidth && this.innerWidth < 1219));
                  if (isSearch) {
                    this.activeTopic = null;
                  } else if (params && params['topic'] && !this.activeTopic) {
                    this.activeTopic = this.stakeholder.topics.find(topic => topic.alias === decodeURIComponent(params['topic']) && this.isPublicOrIsMember(topic.isPublic) && topic.isActive);
                  } else {
                    this.activeTopic = this.stakeholder.topics.find(topic => this.isPublicOrIsMember(topic.isPublic) && topic.isActive);
                  }
                  this.setSideBar();
                } else {
                  this.stakeholderService.setStakeholder(null);
                  LinksResolver.resetProperties();
                  this.navigateToError();
                  this.buildMenu();
                }
              }, error => {
                this.stakeholderService.setStakeholder(null);
                LinksResolver.resetProperties();
                this.navigateToError();
                this.buildMenu();
              });
            } else {
              this.buildMenu();
              if(isSearch) {
                this.activeTopic = null;
              } else if (params && params['topic']) {
                this.activeTopic = this.stakeholder.topics.find(topic => topic.alias === decodeURIComponent(params['topic']) && this.isPublicOrIsMember(topic.isPublic) && topic.isActive);
              } else {
                this.activeTopic = this.stakeholder.topics.find(topic => this.isPublicOrIsMember(topic.isPublic) && topic.isActive);
              }

            }
          } else {
            LinksResolver.resetProperties();
            this.stakeholderService.setStakeholder(null);
            this.layoutService.setOpen(!(this.innerWidth && this.innerWidth < 1219));
            this.stakeholder = null;
            this.buildMenu();
          }
        }));
        this.subscriptions.push(this.userManagementService.getUserInfo().subscribe(user => {
          this.user = user;
          this.buildMenu();
        }, error => {
          console.log("App couldn't fetch properties");
          console.log(error);
        }));
      });
  }
  
  public ngOnDestroy() {
    this.subscriptions.forEach(value => {
      if (value instanceof Subscriber) {
        value.unsubscribe();
      }
    });
  }
  
  private navigateToError() {
    this.router.navigate(['/error'], {queryParams: {'page': this.properties.baseLink + this.router.url}});
  }
  
  public get open() {
    return this.layoutService.open;
  }
  
  public toggleOpen(event: MouseEvent) {
    event.preventDefault();
    this.layoutService.setOpen(!this.open);
  }
  
  private setSideBar() {
    let items: MenuItem[] = [];
    this.stakeholder.topics.forEach((topic) => {
      if (this.isPublicOrIsMember(topic.isPublic) && topic.isActive) {
        let topicItem: MenuItem = new MenuItem(topic.alias, topic.name, "", (
          '/' + this.stakeholder.alias + '/' + topic.alias),
          null, [], [], {});
        topicItem.icon = topic.icon;
        items.push(topicItem);
      }
    });
    if (items.length === 0) {
      items.push(new MenuItem('noTopics', 'No topics available yet', "", "", false, [], [], {}));
    }
    this.sideBarItems = items;
  }
  
  buildMenu() {
    this.menuItems = [];
    this.adminMenuItems = [];
    this.userMenuItems = [];
    if(this.stakeholder) {
      if (this.isFrontPage) {
        this.menuHeader = {
          route: "/" + this.stakeholder.alias,
          url: null,
          title: this.stakeholder.name,
          logoUrl: null,
          logoSmallUrl: null,
          position: 'center',
          badge: false
        };
        // if(this.isAdmin()) {
          this.menuItems.push({
            rootItem: new MenuItem("manage", "Manage",
              "",   "/admin", false, [], null, {}), items: []
          });

        // }
        this.specialSideBarMenuItem  = new MenuItem("search", "Search research outcomes", "",   this.properties.searchLinkToResults, false, [], null, {})
        this.specialSideBarMenuItem.icon = '<span uk-icon="search"></span>';

      } else {
        this.menuHeader = {
          route: "/admin/" + this.stakeholder.alias,
          url: null,
          title: 'Admin - ' + this.stakeholder.name,
          logoUrl: null,
          logoSmallUrl: null,
          position: 'center',
          badge: false
        };
        this.menuItems.push({
          rootItem: new MenuItem("", "Dashboard",
            "", '/'+ this.stakeholder.alias+'/', false, [], null, {}), items: []
        });
        this.adminMenuItems.push(new MenuItem("general", "General", "", "/admin/"+this.stakeholder.alias + '/general', false, [], [], {}, "<i uk-icon=\"image\"></i>"));
        this.adminMenuItems.push(new MenuItem("indicators", "Indicators", "", "/admin/"+this.stakeholder.alias + '/indicators', false, [], [], {}, "<i uk-icon=\"image\"></i>"));
        this.adminMenuItems.push(new MenuItem("users", "Users", "", "/admin/"+this.stakeholder.alias+"/users", false, [], [], {}, "<i uk-icon=\"users\"></i>"));
        this.specialSideBarMenuItem  = new MenuItem("back", "Manage profiles", "", "/admin",false, [], null, {});
        this.specialSideBarMenuItem.icon = '<span class="uk-icon-button uk-icon portal-button  " uk-icon="chevron-left"></span>';

      }
      this.userMenuItems = [];
      /*    if (Session.isPortalAdministrator(this.user)) {
            this.userMenuItems.push(new MenuItem("", "Manage helptexts",
              "", "/helptexts", true, [], [], {communityId:'openaire'}))

          }*/
      if (this.isAdmin()) {
        this.userMenuItems.push(new MenuItem("", "Manage profiles",
          "", "/admin", true, [], [], {}))
        this.specialSideBarMenuItem = null;
      }
      if (this.user) {
        this.userMenuItems.push(new MenuItem("", "User information", "", "/user-info", false, [], [], {}));
      }
    }else{
      if(this.isFrontPage || !this.hasAdminMenu){
        this.menuHeader = { route: null, url: "https://" + (this.properties.environment =='beta'?'beta.':'')+'monitor.openaire.eu', title: "Monitor", logoUrl: 'assets/common-assets/logo-large-monitor.png', logoSmallUrl:"assets/common-assets/logo-small-monitor.png", position:'left' , badge: true };
        //TODO monitor menu items?

      }else{
        this.menuHeader = { route: "/", url: null, title: "Monitor Dashboard", logoUrl: null, logoSmallUrl:null, position:'center' , badge: false };
        this.adminMenuItems = [];
        this.specialSideBarMenuItem = null;
        this.adminMenuItems.push(new MenuItem("stakeholders", "Manage profiles", "", "/admin", false, [], [], {}, "<i uk-icon=\"cog\"></i>"));
        /*let adminOptions = new MenuItem("adminOptions", "Admin Options", "", "", false, [], [], {})
        adminOptions.items.push(new MenuItem("pages", "Pages", "", "/pages", false, [], [], {}));
        adminOptions.items.push(new MenuItem("portals", "Portals", "", "/portals", false, [], [], {}));
        adminOptions.items.push(new MenuItem("entities", "Entities", "", "/entities", false, [], [], {}));
        adminOptions.items.push(new MenuItem("classes", "Class help texts", "", "/classes", false, [], [], {}));
        this.adminMenuItems.push(adminOptions);
        let monitorOptions = new MenuItem("monitorOptions", "Monitor Options", "", "", false, [], [], {})
        monitorOptions.items.push(new MenuItem("pages", "Pages", "", "/pages", false, [], [], {communityId: 'openaire'}));
        monitorOptions.items.push(new MenuItem("entities", "Entities", "", "/entities", false, [], [], {communityId: 'openaire'}));
        monitorOptions.items.push(new MenuItem("classes", "Class help texts", "", "/classContents", false, [], [], {communityId: 'openaire'}));
        monitorOptions.items.push(new MenuItem("helptexts", "Help texts", "", "/helptexts", false, [], [], {communityId: 'openaire'}));
        this.adminMenuItems.push(monitorOptions);*/

      }
    }

  }
  
  public isAdmin() {
    return this.user && (Session.isPortalAdministrator(this.user) || Session.isCommunityCurator(this.user) || Session.isMonitorCurator(this.user));
  }
  
  public isPublicOrIsMember(isPublic: boolean): boolean {
    if (isPublic) {
      return true;
    } else {
      if (this.isViewPublic) { // preview for not members
        return false;
      } else if (this.isAdmin()) {
        // if user is member, return true
        return true;
      }
      return false;
    }
  }

  createSearchParameters(){
    if(!this.stakeholder){
      return {};
    }
    if(this.stakeholder.type == "funder"){
      return { "relfunder":encodeURIComponent("\"" + this.stakeholder.index_id + "||"+this.stakeholder.index_name + "||"+this.stakeholder.index_shortName + "\"" )};
    }else if(this.stakeholder.type == "ri"){
      // https://beta.explore.openaire.eu/search/find/research-outcomes?f0=q&fv0=&resultbestaccessright=%22Open%20Access%22&community=%22mes%7C%7CEuropean%20Marine%20Science%22&qf=true
      return { "community":encodeURIComponent("\"" + this.stakeholder.index_id + "||"+this.stakeholder.index_name + "\"" )};
    }else if(this.stakeholder.type == "organization"){
      return { "cf":true};
    }
  }
}
