/**
 * Created by stefania on 3/21/16.
 */

import {Component, OnInit} from '@angular/core';
import {MenuItem, RootMenuItem, SideMenuItem} from './openaireLibrary/sharedComponents/menu';
import {ActivatedRoute, NavigationStart, Router} from '@angular/router';
import {EnvironmentSpecificService} from './openaireLibrary/utils/properties/environment-specific.service';
import {CommunitiesService} from './openaireLibrary/connect/communities/communities.service';
import {EnvProperties} from './openaireLibrary/utils/properties/env-properties';
import {Session, User} from './openaireLibrary/login/utils/helper.class';
import {HelperFunctions} from './openaireLibrary/utils/HelperFunctions.class';
import {UserManagementService} from './openaireLibrary/services/user-management.service';

declare var UIkit: any;

@Component({
  selector: 'app',
  templateUrl: './app.component.html',
})

export class AppComponent implements OnInit {
  title = 'Metadata Registry Service';
  userMenuItems: MenuItem[] = [];

  menuItems: RootMenuItem [] = [];
  sideMenuItems: SideMenuItem[] = [];
  logInUrl = null;
  logOutUrl = null;
  community: { id: string, name: string, logoUrl: string } = null;
  communityId = '';
  communityType = null;
  properties: EnvProperties = null;
  isPortalAdministrator = false;
  showSidebar: boolean;
  wellcome = false;
  showMenu: boolean = false;
  user: User;

  constructor(private route: ActivatedRoute,
              private propertiesService: EnvironmentSpecificService,
              private _communitiesService: CommunitiesService,
              public router: Router,
              private userManagementService: UserManagementService) {
    this.router.events.forEach((event) => {
      if (event instanceof NavigationStart) {
        HelperFunctions.scroll();
        if (event.url === '/') {
          this.wellcome = true;
        } else {
          this.wellcome = false;
        }
      }
    });
  }

  ngOnInit() {
    this.propertiesService.loadEnvironment()
      .then(es => {
        this.propertiesService.setEnvProperties(es);
        this.properties = this.propertiesService.envSpecific;
        this.logInUrl = this.properties.loginUrl;
        this.logOutUrl = this.properties.logoutUrl;
        this.showSidebar = false;
        this.showMenu = false;
        this.userManagementService.getUserInfo().subscribe(user => {
          this.user = user;
          if (this.user) {
            localStorage.setItem('user_id', this.user.id);
            localStorage.setItem('mining_backend_address', this.properties.miningBackendURL);
            localStorage.setItem('isCommunityManager', Session.isCommunityCurator(this.user) + '');

            this.isPortalAdministrator = Session.isPortalAdministrator(this.user);
          }
          this._communitiesService.updateCommunities(this.properties, this.properties.communityAPI + 'communities');
          this.route.queryParams.subscribe(params => {
            this.communityId = (params['communityId']) ? params['communityId'] : '';

            this.communityType = null;
            this.menuItems = [];
            this.userMenuItems = [];
            this._communitiesService.getCommunitiesState().subscribe(
              communities => {
                //  this.community = community;
                if (!communities || communities.length === 0) {
                  return;
                }
                this.userMenuItems = [];
                let countCommunities = 0;
                let index_managerOfCommunity = null;
                for (let i = 0; i < communities.length; i++) {
                  const com = communities[i];
                  if (Session.isPortalAdministrator(this.user) || Session.isCommunityCurator(this.user)) {
                    this.userMenuItems.push(new MenuItem('manage' + com.communityId, 'Manage ' + ((com.shortTitle) ? com.shortTitle : com.title), '', '/dashboard', false, [], [], {communityId: com.communityId}));
                  } else {
                    for (const manager of com.managers) {
                      if (this.user && manager == this.user.email) {
                        countCommunities++;
                        index_managerOfCommunity = i;
                        this.userMenuItems.push(new MenuItem('manage' + com.communityId, 'Manage ' + ((com.shortTitle) ? com.shortTitle : com.title), '', '/dashboard', false, [], [], {communityId: com.communityId}));
                        break;
                      }
                    }
                  }
                  if (com.communityId === this.communityId) {
                    this.community = {
                      id: com.communityId,
                      name: (com.shortTitle) ? com.shortTitle : com.title,
                      logoUrl: com.logoUrl
                    };
                    this.communityType = com.type;
                    this.menuItems = [
                      {
                        rootItem: new MenuItem('dashboard', 'Overview', '/dashboard', '/dashboard', false, [], null, {communityId: com.communityId}),
                        items: []
                      }
                    ];
                  } else if (countCommunities === 1 && index_managerOfCommunity != null) {
                    this.community = {
                      id: communities[index_managerOfCommunity].communityId,
                      name: (communities[index_managerOfCommunity].shortTitle) ? communities[index_managerOfCommunity].shortTitle : com.title,
                      logoUrl: communities[index_managerOfCommunity].logoUrl
                    };
                    this.menuItems = [
                      {
                        rootItem: new MenuItem('dashboard', 'Overview', '/dashboard', '/dashboard', false, [], null, {communityId: communities[index_managerOfCommunity].communityId}),
                        items: []
                      }
                    ];
                  }
                }
                if (!this.communityId || this.communityId === '') {
                  this.community = null;
                }
                if (this.communityId) {
                  this.userMenuItems.push(new MenuItem('manage-user-notifications', 'Manage notification settings', '', '/manage-user-notifications', false, [], [], {communityId: this.communityId}));
                  this.userMenuItems.push(new MenuItem('personal', 'Manage Personal Info', '', '/personal', false, [], [], {communityId: this.communityId}));
                  this.userMenuItems.push(new MenuItem('', 'Support', 'https://openaire-connect.d4science.org/group/openaire-connect-gateway/explore?siteId=172366611', '', false, [], [], {}));
                }
                this.showMenu = true;
                this.buildSideBar();
              },
              error => {
                if ((this.communityId && this.communityId !== '') || window.location.pathname === '/') {
                  UIkit.notification({
                    message: '<strong>System error retrieving communities.<strong>',
                    status: 'warning',
                    timeout: 3000,
                    pos: 'top-center'
                  });
                }
              }
            );
          });
        });
      });
  }

  private buildSideBar() {
    this.sideMenuItems = [];
    this.showSidebar = false;
    if ((!this.communityId || this.communityId == '') && this.isPortalAdministrator) {
      const adminTools: SideMenuItem = {
        rootItem: new MenuItem('adminTools', 'Admin Tools', '',
          '', false, [], [], null),
        items: [],
        ukIcon: 'desktop'
      };
      adminTools.items.push({
          rootItem: new MenuItem('communities', 'Communities', '/communities',
            '/communities', false, [], [], null),
          items: []
        }
      );
      adminTools.items.push({
          rootItem: new MenuItem('classes', 'Classes', '/classes',
            '/classes', false, [], [], null),
          items: []
        }
      );
      adminTools.items.push({
          rootItem: new MenuItem('pages', 'Pages', '/pages',
            '/pages', false, [], [], null),
          items: []
        }
      );
      adminTools.items.push({
          rootItem: new MenuItem('entities', 'Entities', '/entities',
            '/entities', false, [], [], null),
          items: []
        }
      );
      this.sideMenuItems.push(adminTools);
      this.sideMenuItems.push({
        rootItem: new MenuItem('communities', 'Manage Communities', '/',
          '/', false, [], [], null),
        items: [],
        ukIcon: 'cog'
      });
      this.sideMenuItems.push({
        rootItem: new MenuItem('communities', 'Explore', '',
          '/dashboard', false, [], [], {communityId: 'openaire'}),
        items: [],
        ukIcon: 'cog'
      });
      this.sideMenuItems.push({
        rootItem: new MenuItem('communities', 'Connect', '',
          '/dashboard', false, [], [], {communityId: 'connect'}),
        items: [],
        ukIcon: 'cog'
      });
    } else if (this.communityId && this.communityId !== '') {
      this.sideMenuItems.push({
        rootItem: new MenuItem('overview', 'Overview', '/dashboard',
          '/dashboard', false, [], [], {communityId: this.communityId}),
        items: [],
        ukIcon: 'home'
      });
      if (this.isPortalAdministrator) {
        const adminTools: SideMenuItem = {
          rootItem: new MenuItem('adminTools', 'Admin Tools', '/communities',
            '/communities', false, [], [], null),
          items: [],
          ukIcon: 'desktop'
        };
        this.sideMenuItems.push(adminTools);
      }
      if (this.communityId !== 'openaire' && this.communityId !== 'connect') {
        const community: SideMenuItem = {
          rootItem: new MenuItem('community', 'Community', '',
            '', false, [], [], null),
          items: [],
          ukIcon: 'album'
        };
        community.items.push({
          rootItem: new MenuItem('communityProfile', 'Community Profile', '/community-edit-form',
            '/community-edit-form', false, [], [], {communityId: this.communityId}),
          items: []
        });
        community.items.push({
          rootItem: new MenuItem('communityAffiliations', 'Organizations', '/organizations',
            '/organizations', false, [], [], {communityId: this.communityId}),
          items: []
        });
        /*community.items.push({
          rootItem: new MenuItem('layout', 'Customize Layout', '/customize-layout',
            '/customize-layout', false, [], [], {communityId: this.communityId}),
          items: []
        });*/
        this.sideMenuItems.push(community);
        const communityContent: SideMenuItem = {
          rootItem: new MenuItem('communityContent', 'Community Content', '',
            '', false, [], [], null),
          items: [],
          ukIcon: 'list'
        };
        communityContent.items.push({
            rootItem: new MenuItem('projects', 'Projects', '/manage-projects',
              '/manage-projects', false, [], [], {communityId: this.communityId}),
            items: []
          }
        );
        communityContent.items.push({
          rootItem: new MenuItem('contentProviders', 'Content providers', '/manage-content-providers',
            '/manage-content-providers', false, [], [], {communityId: this.communityId}),
          items: []
        });
        if (this.communityType && this.communityType != 'ri') {
          communityContent.items.push({
            rootItem: new MenuItem('subjects', 'Subjects', '/manage-subjects',
              '/manage-subjects', false, [], [], {communityId: this.communityId}),
            items: []
          });
        }
        communityContent.items.push({
          rootItem: new MenuItem('zenodoCommunities', 'Zenodo communities', '/manage-zenodo-communities',
            '/manage-zenodo-communities', false, [], [], {communityId: this.communityId}),
          items: []
        });
        this.sideMenuItems.push(communityContent);
      }
      const entities: SideMenuItem = {
        rootItem: new MenuItem('entitiesPages', 'Entities & pages', '',
          '', false, [], [], null),
        items: [],
        ukIcon: 'world'
      };
      entities.items.push({
        rootItem: new MenuItem('entities', 'Activate Entities', '/entities',
          '/entities', false, [], [], {communityId: this.communityId}),
        items: []
      });
      const pages: MenuItem[] = [];
      pages.push(new MenuItem('search', 'Search', '/pages',
        '/pages', false, [], [], {communityId: this.communityId, type: 'search'}));
      pages.push(new MenuItem('link', 'Link', '/pages',
        '/pages', false, [], [], {communityId: this.communityId, type: 'link'}));
      pages.push(new MenuItem('share', 'Share', '/pages',
        '/pages', false, [], [], {communityId: this.communityId, type: 'share'}));
      pages.push(new MenuItem('landing', 'Landing', '/pages',
        '/pages', false, [], [], {communityId: this.communityId, type: 'landing'}));
      // pages.push(new MenuItem('html', 'HTML', '/pages',
      //   '/pages', false, [], [], {communityId: this.communityId, type: 'html'}));
      pages.push(new MenuItem('other', 'Other', '/pages',
        '/pages', false, [], [], {communityId: this.communityId, type: 'other'}));
      entities.items.push({
        rootItem: new MenuItem('pages', 'Pages', '/pages',
          '/pages', false, [], [], {communityId: this.communityId}),
        items: pages
      });
      this.sideMenuItems.push(entities);
      const help: SideMenuItem = {
        rootItem: new MenuItem('help', 'Help Texts', '',
          '', false, [], [], null),
        items: [],
        ukIcon: 'file-edit'
      };
      help.items.push({
        rootItem: new MenuItem('pages', 'Page Help Texts', '/pageContents',
          '/pageContents', false, [], [], {communityId: this.communityId}),
        items: []
      });
      if (this.communityId === 'openaire' || this.communityId === 'connect') {
        help.items.push({
          rootItem: new MenuItem('classes', 'Class Help Texts', '/classContents',
            '/classContents', false, [], [], {communityId: this.communityId}),
          items: []
        });
      }
      this.sideMenuItems.push(help);
      if (this.communityId !== 'openaire' && this.communityId !== 'connect') {
        const stats: SideMenuItem = {
          rootItem: new MenuItem('stats', 'Statistics & Charts', '/stats',
            '/stats', false, [], [], {communityId: this.communityId}),
          items: [],
          ukIcon: 'image'
        };
        this.sideMenuItems.push(stats);
        const claims: SideMenuItem = {
          rootItem: new MenuItem('claims', 'Links', '/claims',
            '/claims', false, [], [], {communityId: this.communityId}),
          items: [],
          ukIcon: 'link'
        };
        this.sideMenuItems.push(claims);
        if (this.communityType && this.communityType === 'ri') {
          const mining: SideMenuItem = {
            rootItem: new MenuItem('mining', 'Text Mining Rules', '/mining/manage-profiles',
              '/mining/manage-profiles', false, [], [], {communityId: this.communityId}),
            items: [],
            ukIcon: 'settings'
          };
          this.sideMenuItems.push(mining);
        }
        const users: SideMenuItem = {
          rootItem: new MenuItem('users', 'Users', '',
            '', false, [], [], null),
          items: [],
          ukIcon: 'user'
        };
        users.items.push({
          rootItem: new MenuItem('invite', 'Invite to Subscribe', 'https://beta.' + this.communityId + '.openaire.eu/invite',
            '', false, [], [], null),
          items: []
        });
        users.items.push({
          rootItem: new MenuItem('subscribers', 'Subscribers', '/manage-subscribers',
            '/manage-subscribers', false, [], [], {communityId: this.communityId}),
          items: []
        });
        users.items.push({
          rootItem: new MenuItem('personalInfo', 'Personal Info', '/personal',
            '/personal', false, [], [], {communityId: this.communityId}),
          items: []
        });
        users.items.push({
          rootItem: new MenuItem('notifications', 'Notification settings', '/manage-user-notifications',
            '/manage-user-notifications', false, [], [], {communityId: this.communityId}),
          items: []
        });
        this.sideMenuItems.push(users);
      }
    }
    if (this.sideMenuItems.length > 0) {
      this.showSidebar = true;
    }
  }
}
