import {
  ChangeDetectorRef,
  Component,
  ElementRef,
  Inject,
  OnDestroy,
  OnInit, PLATFORM_ID,
  RendererFactory2,
  ViewChild,
  ViewEncapsulation
} from '@angular/core';
import {ActivatedRoute, NavigationEnd, Router} from '@angular/router';

import {EnvProperties} from './openaireLibrary/utils/properties/env-properties';
import {MenuItem} from './openaireLibrary/sharedComponents/menu';
import {EnvironmentSpecificService} from './openaireLibrary/utils/properties/environment-specific.service';
import {CommunitiesService} from "./openaireLibrary/connect/communities/communities.service";
import {Session, User} from './openaireLibrary/login/utils/helper.class';
import {ConnectHelper} from './openaireLibrary/connect/connectHelper';
import {UserManagementService} from "./openaireLibrary/services/user-management.service";
import {ConfigurationService} from "./openaireLibrary/utils/configuration/configuration.service";
import {properties} from '../environments/environment';
import {Header} from "./openaireLibrary/sharedComponents/navigationBar.component";
import {Subscriber} from "rxjs";
import {CommunityService} from "./openaireLibrary/connect/community/community.service";
import {StringUtils} from "./openaireLibrary/utils/string-utils.class";
import {LoginErrorCodes} from "./openaireLibrary/login/utils/guardHelper.class";
import {Layout} from "./openaireLibrary/connect/community/CustomizationOptions";
import {CustomizationService} from "./openaireLibrary/services/customization.service";
import {SmoothScroll} from "./openaireLibrary/utils/smooth-scroll";
import {makeStateKey, StateKey, TransferState} from "@angular/core";
import {CommunityInfo} from "./openaireLibrary/connect/community/communityInfo";
import {SEOService} from "./openaireLibrary/sharedComponents/SEO/SEO.service";
import {UntypedFormBuilder, UntypedFormGroup, Validators} from "@angular/forms";
import {QuickContactService} from "./openaireLibrary/sharedComponents/quick-contact/quick-contact.service";
import {EmailService} from "./openaireLibrary/utils/email/email.service";
import {AlertModal} from "./openaireLibrary/utils/modal/alert";
import {QuickContactComponent} from "./openaireLibrary/sharedComponents/quick-contact/quick-contact.component";
import {Composer} from "./openaireLibrary/utils/email/composer";
import {NotificationHandler} from "./openaireLibrary/utils/notification-handler";
import {OpenaireEntities} from "./openaireLibrary/utils/properties/searchFields";
import {DOCUMENT, isPlatformServer} from "@angular/common";
import {AdvancedAsyncSubject} from "./openaireLibrary/utils/AdvancedAsyncSubject";
import {LayoutService} from "./openaireLibrary/dashboard/sharedComponents/sidebar/layout.service";
import {Meta} from "@angular/platform-browser";

@Component({
  selector: 'app-root',
  template: `
    <div [class]="(community)?(community.communityId +'App communityApp'):'connectApp'">
      <div id="modal-container"></div>
      <navbar #navbar *ngIf="properties && showMenu && !community && header" [portal]="properties.dashboard" [onlyTop]=false
              [userMenuItems]=userMenuItems [menuItems]=menuItems [user]="user" [header]="header"
              [showMenu]=showMenu [properties]="properties" [showHomeMenuItem]="false" communityId="connect">
          <div *ngIf="showGetStarted" extra-s class="uk-margin-large-top uk-margin-left">
              <a class="uk-button uk-button-primary uk-text-uppercase" routerLink="/get-started" (click)="navbar.closeCanvas()">Get Started</a>
          </div>
        <a *ngIf="showGetStarted" extra-m
           class="uk-button uk-button-small uk-button-primary uk-text-uppercase uk-margin-left"
           routerLink="/get-started">Get Started</a>
      </navbar>
      <navbar *ngIf="properties && showMenu  && community && header" [portal]="community.communityId" [onlyTop]=false
              [communityId]="community.communityId" [header]="header"
              [userMenuItems]=userMenuItems [menuItems]=menuItems [user]="user"
              [showMenu]=showMenu [properties]="properties" [enableSearch]="false"
              searchRoute="/search/find/research-outcomes"
              [showHomeMenuItem]="false">
      </navbar>
      <!--<customization *ngIf="properties &&  showMenu && communityId && communityId.length > 0 && layout" [properties]="properties"
                     [communityId]="communityId" [layout]="layout" ></customization>-->
      <schema2jsonld *ngIf="properties && showMenu && !community" [URL]="properties.domain + properties.baseLink"
                     [logoURL]="properties.domain + properties.baseLink + logoPath + 'main.svg'"
                     type="home"
                     [searchActionRoute]="properties.searchLinkToCommunities" [searchAction]="true"
                     name="OpenAIRE Connect"
                     description="Build a Gateway for your Community: Turn Open Science into Practice. It takes your open and linked research outcomes.">
      </schema2jsonld>
      <schema2jsonld *ngIf="properties  && showMenu && communityId && communityId.length > 0 && community"
                     [URL]="properties.domain + properties.baseLink"
                     [logoURL]="community.logoUrl" type="home" [searchActionRoute]="properties.searchLinkToResults"
                     [name]="(community.shortTitle) ? community.shortTitle : community.title"
                     [description]="community.description">
      </schema2jsonld>
      <div class="custom-main-content">
        <main>
          <router-outlet></router-outlet>
        </main>
      </div>
      <div id="joinAndInviteBtn" *ngIf="isClient && communityId && community">
        <subscribe [communityId]="community.communityId"></subscribe>
        <invite *ngIf="isManager" [longView]="false"></invite>
      </div>
      <!--feedback *ngIf= "isClient && properties" portalName="Connect" [feedbackQuestionaire]=properties.feedbackQuestionaire></feedback-->
      <cookie-law *ngIf="isClient" 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 #bottom *ngIf="properties && isClient && showMenu && !community" [grantAdvance]="false"
              [properties]="properties"></bottom>
      <bottom *ngIf="properties && isClient  && showMenu && community" class=" communityPanelBackground "
              [showSocialButtons]="true" [showMenuItems]="true" [grantAdvance]="false" [showOpenaire]="true"
              [communityId]="community.communityId" [menuItems]=bottomMenuItems [properties]="properties"
              [centered]="true"></bottom>
      <quick-contact #quickContact
                     *ngIf="!community && bottomNotIntersecting && displayQuickContact && showQuickContact && contactForm"
                     (sendEmitter)="send($event)"
                     [contact]="'Help'" [images]="images" [background]="{class: 'uk-background-primary', dark: false}"
                     [contactForm]="contactForm" [sending]="sending"></quick-contact>
      <modal-alert #modal [overflowBody]="false"></modal-alert>
      <role-verification *ngIf="community" service="connect"
                         [id]="community.communityId" [name]="community.title"
                         [type]="community.type"></role-verification>
    </div>
  `
  
})
export class AppComponent implements OnInit, OnDestroy {
  isClient: boolean = false;
  userMenuItems: MenuItem[] = [];
  menuItems: MenuItem [] = [];
  bottomMenuItems: MenuItem[] = [];
  public community: CommunityInfo = null;
  properties: EnvProperties = properties;
  showMenu: boolean = false;
  communities = null;
  user: User;
  communityId: string = "";
  header: Header;
  logoPath: string = 'assets/common-assets/logo-services/connect/';
  public showGetStarted: boolean = true;
  /* Contact */
  public showQuickContact: boolean;
  public bottomNotIntersecting: boolean;
  public displayQuickContact: boolean;  // intersecting with specific section in home page
  public contactForm: UntypedFormGroup;
  public sending = false;
  public images: string[] = [];
  @ViewChild('modal') modal: AlertModal;
  @ViewChild('quickContact') quickContact: QuickContactComponent;
  @ViewChild('bottom', {read: ElementRef}) bottom: ElementRef;
  private subscriptions = [];
  layout: Layout = null;
  layouts: Layout[] = null;
  layoutDefault: Layout = null;
  layoutConnect: Layout = null;
  layoutSub = new AdvancedAsyncSubject<Layout[]>();
  previewLayout = null;
  /**
   * key for portal identity check (client - server: using transfer state
   * */
  key: StateKey<string> = makeStateKey<string>('portal');
  
  constructor(private route: ActivatedRoute, private propertiesService: EnvironmentSpecificService,
              private _communitiesService: CommunitiesService, private smoothScroll: SmoothScroll,
              private router: Router, private userManagementService: UserManagementService,
              private configurationService: ConfigurationService, private _communityService: CommunityService,
              private customizationService: CustomizationService, private _meta: Meta, private seoService: SEOService,
              private quickContactService: QuickContactService,
              private layoutService: LayoutService,
              private fb: UntypedFormBuilder,
              private emailService: EmailService,
              @Inject(DOCUMENT) private document,
              private transferState: TransferState,
              @Inject(PLATFORM_ID) private platformId: any,
              private rendererFactory: RendererFactory2,
              private cdr: ChangeDetectorRef
  ) {
    this.subscriptions.push(router.events.forEach((event) => {
      if (event instanceof NavigationEnd) {
        if (event.url === '/contact-us') {
          this.quickContactService.setDisplay(false);
        } else if (event.url !== '/contact-us' && !this.showQuickContact) {
          this.quickContactService.setDisplay(true);
        }
        this.showGetStarted = event.url !== '/get-started';
      }
    }));
    this.getLayouts();
  }
  
  ngOnInit() {
    this.subscriptions.push(this.route.queryParams.subscribe(data => {
      this.previewLayout = (data['previewLayout'] && data['previewLayout'].length > 0 ? data['previewLayout'] : null);
      if (this.properties.environment == "production" || this.properties.environment == "development") {
        this._meta.updateTag({content: 'all', name: 'robots'});
        this.seoService.removeLinkForPrevURL();
        this.seoService.removeLinkForNextURL();
      }
    }));
    this._communitiesService.updateCommunities(this.properties, this.properties.communitiesAPI);
    if (typeof document !== 'undefined') {
      try {
        this.isClient = true;
      } catch (e) {
      }
    }
    this.subscriptions.push(this.userManagementService.getUserInfo().subscribe(user => {
      this.user = user;
      this.init();
    }, error => {
      this.init();
    }));
    this.subscriptions.push(this.layoutService.hasQuickContact.subscribe(hasQuickContact => {
      if (this.showQuickContact !== hasQuickContact) {
        this.showQuickContact = hasQuickContact;
        this.cdr.detectChanges();
      }
    }));
    this.subscriptions.push(this.quickContactService.isDisplayed.subscribe(display => {
      if (this.displayQuickContact !== display) {
        this.displayQuickContact = display;
        this.cdr.detectChanges();
      }
    }));
  }
  
  ngOnDestroy() {
    this.subscriptions.forEach(subscription => {
      if (subscription instanceof Subscriber) {
        subscription.unsubscribe();
      } else if (typeof IntersectionObserver !== "undefined" && subscription instanceof IntersectionObserver) {
        subscription.disconnect();
      }
    });
    this._communitiesService.clearSubscriptions();
    this.userManagementService.clearSubscriptions();
    this.configurationService.clearSubscriptions();
    this._communityService.clearSubscriptions();
    this.smoothScroll.clearSubscriptions();
  }
  
  createObservers() {
    let options = {
      root: null,
      rootMargin: '0px',
      threshold: 0.1
    };
    let intersectionObserver = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        if (this.bottomNotIntersecting !== (!entry.isIntersecting)) {
          this.bottomNotIntersecting = !entry.isIntersecting;
          this.cdr.detectChanges();
        }
      });
    }, options);
    if (this.bottom) {
      intersectionObserver.observe(this.bottom.nativeElement);
      this.subscriptions.push(intersectionObserver);
    }
  }
  
  get isManager() {
    return Session.isCommunityCurator(this.user) || Session.isPortalAdministrator(this.user) || (this.communityId && Session.isManager('community', this.communityId, this.user))
  }
  
  get isPrivate() {
    return this.community && !ConnectHelper.isPrivate(this.community, this.user)
  }
  
  private init() {
    let communityId: string = ConnectHelper.getCommunityFromDomain(this.properties.domain);
    this.showMenu = false;
    // this.initAdminToolCommunity(communityId);
    this.buildMenu(communityId);
    // this.communityId = communityId;
    if (!communityId) {
      this.reset();
      this.userManagementService.fixRedirectURL = properties.afterLoginRedirectLink;
    } else {
      this.userManagementService.fixRedirectURL = null;
    }
  }
  
  initCss(communityId, suffix = null) {
    try {
      const renderer = this.rendererFactory.createRenderer(this.document, {
        id: '-1',
        encapsulation: ViewEncapsulation.None,
        styles: [],
        data: {}
      });
      const head = this.document.getElementsByTagName('head')[0];
      if (head === null) {
        throw new Error('<head> not found within DOCUMENT.');
      }
      if (!this.document.getElementById("dashboardStyle")) {
        const script = renderer.createElement('link');
        renderer.setAttribute(script, "id", "dashboardStyle");
        renderer.setAttribute(script, "href", ((communityId) ? communityId : this.properties.adminToolsPortalType) + (suffix ? "-" + suffix : "") + ".css");
        renderer.setAttribute(script, "rel", "stylesheet");
        renderer.appendChild(head, script);
      } else if (!this.previewLayout) {
        this.document.getElementById("dashboardStyle").href = ((communityId) ? communityId : this.properties.adminToolsPortalType) + (suffix ? "-" + suffix : "") + ".css";
      }
    } catch (e) {
      console.error('Renderrer Error to append style ', e);
    }
  }
  
  initAdminToolCommunity(communityId) {
    if (communityId) {
      this.properties.adminToolsPortalType = "community";
      if (this.document) {
        this.initLayout(communityId);
      }
    } else {
      this.properties.adminToolsPortalType = "connect";
      if (this.document) {
        this.initLayout(this.communityId?this.communityId:'connect');
      }
    }
    this.configurationService.initPortal(this.properties, (communityId) ? communityId : this.properties.adminToolsPortalType);
  }
  
  getLayouts() {
    this.customizationService.getLayouts(this.properties).subscribe(
      layouts => {
        this.layouts = layouts;
        this.layoutDefault = layouts.filter(layout => layout.portalPid == 'default')[0];
        this.layoutConnect = layouts.filter(layout => layout.portalPid == 'connect')[0];
        this.layoutSub.next(this.layouts);
      },
      error => {
        this.layoutSub.next([]);
      }
    );
  }
  
  initLayout(communityId) {
    let portal = this.transferState.get<string>(this.key, null);
    if(isPlatformServer(this.platformId)) {
      this.transferState.set(this.key, communityId);
    }
    if (!this.layout && (portal !== communityId) && !this.previewLayout) {
      // if((typeof location == 'undefined') && !this.previewLayout) {
      this.subscriptions.push(this.layoutSub.subscribe(value => {
        this.layouts = value;
        this.layout = this.layouts.filter(layout => layout.portalPid == communityId)[0] ? this.layouts.filter(layout => layout.portalPid == communityId)[0] : this.layouts.filter(layout => layout.portalPid == 'default')[0];
        this.initCss(this.layout.portalPid, this.layout.date ? this.layout.date : null)
      }));
      
    } else if (this.previewLayout && this.previewLayout.split("-preview-")[0] == communityId) {
      this.initCss(communityId, this.previewLayout.split(communityId)[1]);
    }
  }
  
  public buildMenu(communityId: string) {
    if (communityId) {
      if (!this.community || this.communityId !== communityId) {
        this.subscriptions.push(this._communityService.getCommunity(communityId).subscribe(community => {
          if (community) {
            this.community = community;
          } else {
            this.community = null;
            this.communityId = null;
          }
          this.buildCommunityMenu();
        }));
      } else {
        this.buildCommunityMenu();
      }
    } else {
      this.buildConnectMenu();
    }
  }
  
  buildCommunityMenu() {
    if (this.community && !ConnectHelper.isPrivate(this.community, this.user)) {
      this.communityId = this.community.communityId;
      this.initAdminToolCommunity(this.communityId);
      this.header = {
        // url: 'https://' + (this.properties.environment == 'beta' ? 'beta.' : '') + this.community.id + '.openaire.eu',
        route: "/",
        title: (this.community.shortTitle) ? this.community.shortTitle : this.community.title,
        logoUrl: (this.community.isUpload) ? (properties.utilsService + '/download/' + this.community.logoUrl) : (StringUtils.urlPrefix(this.community.logoUrl) + this.community.logoUrl),
        logoSmallUrl: (this.community.isUpload) ? (properties.utilsService + '/download/' + this.community.logoUrl) : (StringUtils.urlPrefix(this.community.logoUrl) + this.community.logoUrl),
        position: 'left',
        badge: true
      };
      this.menuItems = [];
      this.menuItems.push(
        new MenuItem("dashboard", "Home",
          "", "/", false, [], null, {}
          , null, null, null, null)
      );
      this.menuItems.push(
        new MenuItem("deposit", "Deposit", "", "/participate/deposit/learn-how", false, [], ["/participate/deposit/learn-how"], {}),
      );
      this.menuItems.push(
        new MenuItem("link", "Link", "", "/participate/claim", false, [], ["/participate/claim"], {},
          null, null, null, null, "_blank", "internal", false,
          [
            new MenuItem("", "Start linking", "", "/participate/claim", false, [], ["/participate/claim"], {}),
            new MenuItem("", "Learn more", this.properties.claimsInformationLink, "", false, [], [], {})
          ]
        )
      );
      this.menuItems.push(
        new MenuItem("search", "Search", "", "/search/find", false, [], ["/search/find"], {},
          null, null, null, null, "_blank", "internal", false,
          [
            new MenuItem("", OpenaireEntities.RESULTS, "", "/search/find/research-outcomes", false, [], ["/search/find/research-outcomes"], {resultbestaccessright: '"' + encodeURIComponent("Open Access") + '"'}),
            new MenuItem("", OpenaireEntities.PROJECTS, "", "/search/find/projects/", false, ["project"], ["/search/find/projects"], {}),
            new MenuItem("", OpenaireEntities.DATASOURCES, "", "/search/find/dataproviders", false, ["datasource"], ["/search/find/dataproviders"], {}),
          ]
        ));
      this.menuItems.push(
        new MenuItem("about", "About", "", "", false, [], [], {},
          null, null, null, null, "_blank", "internal", false,
          [
            new MenuItem("", "Supporting organizations", "", "/organizations", false, [], ["/organizations"], {}),
            new MenuItem("", "Curators", "", "/curators", false, [], ["/curators"], {}),
            new MenuItem("", "Sources and methodology", "", "/content", false, [], ["/content"], {}),
            new MenuItem("", "National Bulletins", "", "/national-bulletins", false, [], ["/national-bulletins"], {}),
            new MenuItem("", "Subjects", "", "/subjects", false, [], ["/subjects"], {}),
            new MenuItem("", "Projects and funding Opportunities", "", "/projects", false, [], ["/projects"], {}),
            new MenuItem("", "Fields of Science", "", "/fields-of-science", false, [], ["/fields-of-science"], {}),
            new MenuItem("", "Sustainable Development Goals", "", "/sdgs", false, [], ["/sdgs"], {}),
            new MenuItem("", "FAQs", "", "/faqs", false, [], ["/faqs"], {}),
            new MenuItem("", "Roadmap", "", "/roadmap", false, [], ["/roadmap"], {}),
          ]
        ));
      this.menuItems.push(
        new MenuItem("develop", "Develop", "", "/develop", false, [], ["/develop"], {}),
      );
      if (this.isManager) {
        this.menuItems.push(
          new MenuItem("manage", "Manage", this.properties.adminPortalURL + '/' + this.community.communityId, "", false, [], [], {}, null, null, null, null, "_self"),
        );
      }
      this.bottomMenuItems = [
        new MenuItem("", "Supporting organizations", "", "/organizations", false, [], ["/organizations"], {})
      ];
      if (this.properties.showContent) {
        this.bottomMenuItems.push(new MenuItem("", "Sources and methodology", "", "/content", false, [], [], {}));
      }
      if (this.user) {
        this.userMenuItems = [ /*new MenuItem("","My profile","","",false,[],[],{}),*/
          new MenuItem("", "My ORCID links", "", "/my-orcid-links", false, [], [], {}),
          new MenuItem("", "My links", "", "/myclaims", false, [], ["/myclaims"], {}),
          new MenuItem("", "Invite users", "", "/invite", false, [], [], {}),
        ];
        if (this.isManager) {
          this.userMenuItems.push(new MenuItem("", "Support", "https://tools.openaire.eu/group/openaire_rcd", "", false, [], [], {}))
        }
      }
      this.showMenu = true;
    } else {
      this.communityId = (this.community && ConnectHelper.isPrivate(this.community, this.user))?this.community.communityId:null;
      this.configurationService.initPortal(this.properties, "connect");
      this.buildConnectMenu(true);
      if (this.community && this.community.isRestricted()) {
        if (!this.user) {
          if (typeof location !== 'undefined' && location.pathname.indexOf("user-info") == -1) {
            this.router.navigate(['/user-info'], {
              queryParams: {
                "errorCode": LoginErrorCodes.NOT_LOGIN,
                "redirectUrl": location.pathname + location.search + location.hash
              }
            });
          }
        } else {
          if (typeof location !== 'undefined' && location.pathname.indexOf("user-info") == -1) {
            this.router.navigate(['/'], {queryParamsHandling: "merge"});
          }
        }
      } else if (this.community && (this.community.isPrivate())) {
        this.router.navigate([this.properties.errorLink]);
      } else {
        this.router.navigate(['/'], this.community && this.community.status ? {queryParamsHandling: "merge"} : {});
      }
    }
  }
  
  buildConnectMenu(restrictedData: boolean = false) {
    this.initAdminToolCommunity(null);
    let url = "https://" + (properties.environment != "production" ? "beta." : "") + "connect.openaire.eu";
    this.header = {
      route: restrictedData ? "" : "/",
      url: restrictedData ? url : "",
      title: 'connect',
      logoUrl: this.logoPath + 'main.svg',
      logoSmallUrl: this.logoPath + 'small.svg',
      position: 'left',
      badge: true
    };
    this.menuItems = [];
    this.menuItems.push(
      new MenuItem("about", "About", restrictedData ? url + "/about/learn-how" : "", restrictedData ? "" : "/about/learn-how", false, [], ["/about/learn-how"], {},
        null, null, null, null, "_blank", "internal", false,
        [
          new MenuItem("", "Learn the process", restrictedData ? url + "/about/learn-how" : "", restrictedData ? "" : "/about/learn-how", false, [], ["/about/learn-in-depth"], {}),
          new MenuItem("", "Publications", restrictedData ? url + "/publications" : "", restrictedData ? "" : "/publications", false, [], ["/publications"], {}),
          new MenuItem("", "Roadmap", "https://trello.com/b/yfzUz0kp/openaire-connect-dashboard", "", false, [], [], {}),
          new MenuItem("", "FAQs", restrictedData ? url + "/about/faq" : "", restrictedData ? "" : "/about/faq", false, [], ["/about/faq"], {})
        ]
      )
    );
    this.menuItems.push(
      new MenuItem("communities", "Communities", restrictedData ? url + "/search/find/communities" : "", restrictedData ? "" : "/search/find/communities", false, [], ['/search/find/communities'], {}),
    );
    this.bottomMenuItems = [
      new MenuItem("", "About", "https://openaire.eu/project-factsheets", "", false, [], [], {}),
      new MenuItem("", "News - Events", "https://openaire.eu/news-events", "", false, [], [], {}),
      new MenuItem("", "Blog", "https://blogs.openaire.eu/", "", false, [], [], {}),
      new MenuItem("", "Contact us", restrictedData ? url + "/contact-us" : "", restrictedData ? "" : "/contact-us", false, [], [], {})
    ];
    this.userMenuItems = [];
    if (Session.isPortalAdministrator(this.user)) {
      this.userMenuItems.push(new MenuItem("", "Manage Helptexts",
        properties.adminPortalURL + "/connect/admin-tools/pages", "", false, [], [], {}))
    }
    if (this.user) {
      this.userMenuItems.push(new MenuItem("my-communities", "My Communities", restrictedData ? url + "/myCommunities" : "",
        restrictedData ? "" : "/myCommunities", false, [], [], {}));
    }
    this.showMenu = true;
    if (typeof IntersectionObserver !== "undefined") {
      setTimeout(() => {
        this.createObservers();
      });
    }
  }
  
  /**
   * Contact methods
   * */
  public send(event) {
    if (event.valid === true) {
      this.sendMail(this.properties.admins);
    }
  }
  
  public reset() {
    if (this.quickContact) {
      this.quickContact.close();
    }
    this.contactForm = this.fb.group({
      name: this.fb.control('', Validators.required),
      surname: this.fb.control('', Validators.required),
      email: this.fb.control('', [Validators.required, Validators.email]),
      affiliation: this.fb.control('', Validators.required),
      community: this.fb.control('', Validators.required),
      message: this.fb.control('', Validators.required),
      recaptcha: this.fb.control('', Validators.required)
    });
  }
  
  private sendMail(admins: string[]) {
    this.sending = true;
    this.subscriptions.push(this.emailService.contact(this.properties,
      Composer.composeEmailForNewCommunity(this.contactForm.value, admins),
      this.contactForm.value.recaptcha).subscribe(
      res => {
        if (res) {
          this.sending = false;
          this.reset();
          this.modalOpen();
        } else {
          this.handleError('Email <b>sent failed!</b> Please try again.');
        }
      },
      error => {
        this.handleError('Email <b>sent failed!</b> Please try again.', error);
      }
    ));
  }
  
  public modalOpen() {
    this.modal.okButton = true;
    this.modal.alertTitle = 'Your request has been successfully submitted';
    this.modal.message = 'Our team will respond to your submission soon.';
    this.modal.alertMessage = true;
    this.modal.cancelButton = false;
    this.modal.okButtonLeft = false;
    this.modal.okButtonText = 'OK';
    this.modal.open();
  }
  
  handleError(message: string, error = null) {
    if (error) {
      console.error(error);
    }
    this.sending = false;
    this.quickContact.close();
    NotificationHandler.rise(message, 'danger');
    this.contactForm.get('recaptcha').setValue('');
  }
}
