import {ChangeDetectorRef, Component, HostListener, 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, Visibility} from "./openaireLibrary/monitor/entities/stakeholder";
import {LinksResolver} from "./search/links-resolver";
import {Header} from "./openaireLibrary/sharedComponents/navigationBar.component";
import {arrow_left} from "./openaireLibrary/utils/icons/icons";
import {properties} from "../environments/environment";
import {ConfigurationService} from "./openaireLibrary/utils/configuration/configuration.service";


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit, OnDestroy {
  properties: EnvProperties = properties;
  user: User;
  params: BehaviorSubject<Params> = new BehaviorSubject<Params>(null);
  hasSidebar: boolean = false;
  hasHeader: boolean = false;
  hasAdminMenu: boolean = false;
  isFrontPage: boolean = false;
  isDashboard: 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,
    stickyAnimation: false
  };
  
  userMenuItems: MenuItem[] = [];
  adminMenuItems: MenuItem[] = [];
  stakeholder: Stakeholder = null;
  activeTopic: Topic = null;
  loading: boolean = true;
  paramsResolved: boolean = false;
  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,  private configurationService: ConfigurationService) {
    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.paramsResolved = true;
        this.params.next(params);
      }
    }));
  }
  
  @HostListener('window:resize', ['$event'])
  onResize(event) {
    if (this.layoutService.isSmallScreen && event.target.innerWidth > 1219) {
      this.layoutService.setSmallScreen(false);
    } else if (!this.layoutService.isSmallScreen && event.target.innerWidth < 1219) {
      this.layoutService.setSmallScreen(true);
      this.layoutService.setOpen(false);
    }
  }
  
  ngOnInit() {
    if (typeof document !== 'undefined' && window) {
      this.innerWidth = window.innerWidth;
    }
    this.subscriptions.push(this.layoutService.hasSidebar.subscribe(hasSidebar => {
      this.hasSidebar = hasSidebar;
      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.isFrontPage.subscribe(isFrontPage => {
      this.isFrontPage = isFrontPage;
      this.cdr.detectChanges();
    }));
    this.subscriptions.push(this.layoutService.isDashboard.subscribe(isDashboard => {
      this.isDashboard = isDashboard;
      this.cdr.detectChanges();
    }));
    this.route.queryParams.subscribe(params => {
      this.isViewPublic = (params['view'] == 'public');
    });
    this.layoutService.setSmallScreen((this.innerWidth && this.innerWidth < 1219));
    this.layoutService.setOpen(!(this.innerWidth && this.innerWidth < 1219));
    this.subscriptions.push(this.params.subscribe(params => {
      if (this.paramsResolved) {
        this.loading = true;
        let isSearch = this.router.url.includes('/search/');
        if (params && params['stakeholder']) {
          // this.stakeholder = this.stakeholderService.stakeholder;
          if (!this.stakeholder || this.stakeholder.alias !== params['stakeholder']) {
            this.subscriptions.push(this.stakeholderService.getStakeholder(params['stakeholder']).subscribe(stakeholder => {
              if (stakeholder) {
                this.stakeholder = stakeholder;
                LinksResolver.setProperties(this.stakeholder.alias);
                this.setProperties(this.stakeholder.type, this.stakeholder.alias);
                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.visibility));
                } else {
                  this.activeTopic = this.stakeholder.topics.find(topic => this.isPublicOrIsMember(topic.visibility));
                }
                this.setSideBar();
                this.buildMenu();
                this.loading = false;
              } else {
                this.stakeholder = null;
                LinksResolver.resetProperties();
                this.resetProperties();
                this.navigateToError();
                this.buildMenu();
                this.loading = false;
              }
            }));
          } 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.visibility));
            } else {
              this.activeTopic = this.stakeholder.topics.find(topic => this.isPublicOrIsMember(topic.visibility));
            }
            this.loading = false;
          }
        } else {
          LinksResolver.resetProperties();
          this.stakeholderService.setStakeholder(null);
          this.layoutService.setOpen(!(this.innerWidth && this.innerWidth < 1219));
          this.stakeholder = null;
          this.buildMenu();
          this.loading = false;
          this.resetProperties();
        }
      }
    }));
    this.subscriptions.push(this.userManagementService.getUserInfo().subscribe(user => {
      this.user = user;
      if (user) {
        this.buildMenu();
      }
    }));
  }
  
  public ngOnDestroy() {
    this.subscriptions.forEach(value => {
      if (value instanceof Subscriber) {
        value.unsubscribe();
      }
    });
    this.userManagementService.clearSubscriptions();
    this.layoutService.clearSubscriptions();
    this.stakeholderService.clearSubscriptions();
    this.configurationService.clearSubscriptions();
  }
  
  private navigateToError() {
    this.router.navigate(['/error'], {queryParams: {'page': this.properties.baseLink + this.router.url}});
  }
  
  public get open() {
    return this.layoutService.open;
  }
  
  private setSideBar() {
    let items: MenuItem[] = [];
    if (this.isPublicOrIsMember(this.stakeholder.visibility)) {
      this.stakeholder.topics.forEach((topic) => {
        if (this.isPublicOrIsMember(topic.visibility)) {
          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, [], [], {}));
      }
    } else {
      let topicItem: MenuItem = new MenuItem("private", "Private Data", "", "", null, [], [], {});
      items.push(topicItem);
    }
    this.sideBarItems = items;
  }
  
  buildMenu() {
    this.menuItems = [];
    this.adminMenuItems = [];
    this.userMenuItems = [];
    if (this.user) {
      if (this.isCurator()) {
        this.userMenuItems.push(new MenuItem("", "Manage profiles",
          "", "/admin", false, [], [], {}));
      }
      if(Session.isPortalAdministrator(this.user) ) {
        this.userMenuItems.push( new MenuItem("adminOptions", "Super Admin options","", "/admin/admin-tools/portals", false, [], [], {}));
        this.userMenuItems.push(new MenuItem("monitorOptions", "Monitor portal options","", "/admin/monitor/admin-tools/pages", false, [], [], {}));

      }
      this.userMenuItems.push(new MenuItem("", "User information", "", "/user-info", false, [], [], {}));
    }
    if (this.stakeholder) {
      if (!this.isDashboard) {
        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,
          stickyAnimation: false
        };
        this.menuItems.push({
          rootItem: new MenuItem("dashboard", "Dashboard",
            "", "/" + this.stakeholder.alias, false, [], null, {}), items: []
        });
        if(this.stakeholder.type === "funder") {
          this.menuItems.push({
            rootItem: new MenuItem("develop", "Develop",
              "", "/" + this.stakeholder.alias + "/develop", false, [], null, {}), items: []
          });
        }
        if (this.isCurator()) {
          this.menuItems.push({
            rootItem: new MenuItem("manage", "Manage",
              "", "/admin", false, [], null, {}), items: []
          });
        }
      }
      else if (this.isFrontPage) {
        this.menuHeader = {
          route: "/" + this.stakeholder.alias,
          url: null,
          title: this.stakeholder.name,
          logoUrl: null,
          logoSmallUrl: null,
          position: 'center',
          badge: false,
          stickyAnimation: false
        };
        if(this.stakeholder.type === "funder") {
          this.menuItems.push({
            rootItem: new MenuItem("develop", "Develop",
              "", "/" + this.stakeholder.alias + "/develop", false, [], null, {}), items: []
          });
        }
        if (this.isCurator()) {
          this.menuItems.push({
            rootItem: new MenuItem("manage", "Manage",
              "", "/admin", false, [], null, {}), items: []
          });
        }
        
        if (this.isPublicOrIsMember(this.stakeholder.visibility)) {
          this.specialSideBarMenuItem = new MenuItem("search", "Search research outcomes", "", this.properties.searchLinkToResults, false, [], null, {});
          this.specialSideBarMenuItem.icon = '<span uk-icon="search"></span>';
        } else {
          this.specialSideBarMenuItem = null;
        }
      } else {
        this.menuHeader = {
          route: "/admin/" + this.stakeholder.alias,
          url: null,
          title: 'Admin - ' + this.stakeholder.name,
          logoUrl: null,
          logoSmallUrl: null,
          position: 'center',
          badge: false,
          stickyAnimation: 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, false, [], [], {}, "<i uk-icon=\"image\"></i>"));
        this.adminMenuItems.push(new MenuItem("indicators", "Indicators", "", "/admin/" + this.stakeholder.alias + '/indicators', false, [], [], {}, "<i uk-icon=\"image\"></i>"));
        if(this.stakeholder.defaultId) {
          this.adminMenuItems.push(new MenuItem("users", "Users", "", "/admin/" + this.stakeholder.alias + "/users", false, [], [], {}, "<i uk-icon=\"users\"></i>"));
          if (Session.isPortalAdministrator(this.user)) {
            this.adminMenuItems.push(new MenuItem("admin-tools", "Pages & Entities", "", "/admin/" + this.stakeholder.alias + "/admin-tools/pages", false, [], [], {}, null, null, null, "/admin/" + this.stakeholder.alias + "/admin-tools"));
          }
        }
        this.specialSideBarMenuItem = new MenuItem("back", "Manage profiles", "", "/admin", false, [], null, {});
        this.specialSideBarMenuItem.icon = '<span class="uk-icon-button small uk-icon uk-button-secondary">' + arrow_left.data + '</span>'; // '<span class="uk-icon-button uk-icon portal-button  " uk-icon="chevron-left"></span>';
        this.specialSideBarMenuItem.customClass = 'uk-text-uppercase uk-text-bold uk-text-secondary';
      }
    } 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,
          stickyAnimation: false
        };
        this.menuItems.push({
          rootItem: new MenuItem("about", "About",
            "https://" + (this.properties.environment == 'beta' ? 'beta.' : '') + 'monitor.openaire.eu/about/learn-how', "", false, [], null, {}),
          items: []
        });
        this.menuItems.push({
          rootItem: new MenuItem("browse", "Browse",
            "https://" + (this.properties.environment == 'beta' ? 'beta.' : '') + 'monitor.openaire.eu/browse', "", false, [], null, {}),
          items: []
        });
        this.menuItems.push({
          rootItem: new MenuItem("contact", "Contact us",
            "https://" + (this.properties.environment == 'beta' ? 'beta.' : '') + 'monitor.openaire.eu/contact-us', "", false, [], null, {}),
          items: []
        });
      } else {
        this.menuHeader = {
          route: "/",
          url: null,
          title: "Monitor Dashboard",
          logoUrl: null,
          logoSmallUrl: null,
          position: 'center',
          badge: false,
          stickyAnimation: false
        };
        this.adminMenuItems = [];
        this.specialSideBarMenuItem = null;
        this.adminMenuItems.push(new MenuItem("stakeholders", "Manage profiles", "", "/admin", false, [], [], {}, "<i uk-icon=\"cog\"></i>"));
//        if(Session.isPortalAdministrator(this.user) ) {
//          let adminOptions = new MenuItem("adminOptions", "Admin Options","", "/admin-tools/admin-pages", false, [], [], {});
// /*         adminOptions.items.push(new MenuItem("pages", "Pages", "", "/admin-tools/pages", false, [], [], {}));
//          adminOptions.items.push(new MenuItem("portals", "Portals", "", "/admin-tools/portals", false, [], [], {}));
//          adminOptions.items.push(new MenuItem("entities", "Entities", "", "/admin-tools/entities", false, [], [], {}));
//          // adminOptions.items.push(new MenuItem("classes", "Class help texts", "", "/admin-tools/classes", false, [], [], {}));*/
//          this.adminMenuItems.push(adminOptions);
//          let monitorOptions = new MenuItem("monitorOptions", "Monitor Options","", "/admin-tools/admin-pages", false, [], [], {communityId: 'monitor'});
//         /* monitorOptions.items.push(new MenuItem("pages", "Pages", "", "/admin-tools/pages", false, [], [], {communityId: 'monitor'}));
//          monitorOptions.items.push(new MenuItem("entities", "Entities", "", "/admin-tools/entities", false, [], [], {communityId: 'monitor'}));
//          // monitorOptions.items.push(new MenuItem("classes", "Class help texts", "", "/admin-tools/classContents", false, [], [], {communityId: 'monitor'}));
//          monitorOptions.items.push(new MenuItem("helptexts", "Help texts", "", "/admin-tools/helptexts", false, [], [], {communityId: 'monitor'}));*/
//          this.adminMenuItems.push(monitorOptions);
//        }
        
      }
    }
    
  }
  
  public isCurator() {
    return this.user && (Session.isPortalAdministrator(this.user) || Session.isMonitorCurator(this.user) || Session.isKindOfMonitorManager(this.user));
  }
  
  public isManager(stakeholder: Stakeholder) {
    return this.user && (Session.isPortalAdministrator(this.user) || Session.isCurator(stakeholder.type, this.user) || Session.isManager(stakeholder.type, stakeholder.alias, this.user));
  }
  
  private resolvePageInner() {
    if (document !== undefined) {
      let header = document.getElementById('pager_header_content');
      let inner = document.getElementById('page_content_inner');
      if (header) {
        inner.setAttribute('style', '{margin-top:' + header.offsetHeight + '}');
      } else {
        inner.setAttribute('style', '{margin-top:' + 0 + '}');
      }
    }
  }
  
  public isPublicOrIsMember(visibility: Visibility): boolean {
    if (visibility == "PRIVATE" || (this.isViewPublic && visibility != "PUBLIC")) {
      return false;
    }
    return true;
  }
  setProperties(type, communityId){
    this.properties.adminToolsCommunity = communityId;
    this.properties.adminToolsPortalType = type;
    this.configurationService.initCommunityInformation(this.properties, this.properties.adminToolsCommunity);
  }
  resetProperties(){
    this.properties.adminToolsCommunity = "monitor";
    this.properties.adminToolsPortalType = "monitor";
    this.configurationService.initCommunityInformation(this.properties, this.properties.adminToolsCommunity);
  }
  
  /*  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") {
        return {"community": encodeURIComponent("\"" + this.stakeholder.index_id + "||" + this.stakeholder.index_name + "\"")};
      } else if (this.stakeholder.type == "organization") {
        return {"cf": true};
      }
    }*/
}
