import {AfterViewInit, Component, ElementRef, OnDestroy, OnInit, QueryList, ViewChild, ViewChildren} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {Meta, Title} from '@angular/platform-browser';
import {EnvProperties} from '../openaireLibrary/utils/properties/env-properties';
import {CommunitiesService} from '../openaireLibrary/connect/communities/communities.service';
import {CommunityInfo} from '../openaireLibrary/connect/community/communityInfo';

import {PiwikService} from '../openaireLibrary/utils/piwik/piwik.service';
import {StringUtils} from '../openaireLibrary/utils/string-utils.class';

import {ErrorCodes} from '../openaireLibrary/utils/properties/errorCodes';
import {ErrorMessagesComponent} from '../openaireLibrary/utils/errorMessages.component';
import {HelperService} from "../openaireLibrary/utils/helper/helper.service";
import {SEOService} from "../openaireLibrary/sharedComponents/SEO/SEO.service";
import {properties} from "../../environments/environment";
import {Subscriber} from "rxjs";
import {Session, User} from "../openaireLibrary/login/utils/helper.class";
import {UserManagementService} from "../openaireLibrary/services/user-management.service";
import {QuickContactService} from "../openaireLibrary/sharedComponents/quick-contact/quick-contact.service";
import {StakeholderInfo} from "../openaireLibrary/monitor/entities/stakeholder";
import {OpenaireEntities} from "../openaireLibrary/utils/properties/searchFields";

@Component({
  selector: 'communities',
  templateUrl: 'communities.component.html',
	styleUrls: ['communities.component.less']
})

export class CommunitiesComponent implements OnInit, OnDestroy, AfterViewInit {
  private subscriptions = [];
  private user: User;
  public pageTitle = "OpenAIRE"
  public researchCommunities: CommunityInfo[] = [];
  public pageContents = null;
  public divContents = null;
  // Message variables
  public status: number;
  public loading: boolean = true;
  public subscriberErrorMessage: string = "";
  public errorCodes: ErrorCodes;
  private errorMessages: ErrorMessagesComponent;
	@ViewChildren('scrolling_element') elements: QueryList<ElementRef>;
  @ViewChild('contact') contact: ElementRef;
  public entities = OpenaireEntities;
  public properties: EnvProperties = properties;
  public keyword: string = "";
  public type: string = "all";

  constructor(
    private route: ActivatedRoute,
    private _router: Router,
    private _meta: Meta,
    private _title: Title,
    private _piwikService: PiwikService,
    private _communitiesService: CommunitiesService,
    private helper: HelperService,
    private seoService: SEOService,
    private userManagementService: UserManagementService,
    private quickContactService: QuickContactService) {

    var description = "OpenAIRE - Connect, Community Dashboard, research community";
    var title = "OpenAIRE - Connect";

    this._meta.updateTag({content: description}, "name='description'");
    this._meta.updateTag({content: description}, "property='og:description'");
    this._meta.updateTag({content: title}, "property='og:title'");
    this._title.setTitle(title);

    this.errorCodes = new ErrorCodes();
    this.errorMessages = new ErrorMessagesComponent();
    this.status = this.errorCodes.LOADING;
    this.quickContactService.setDisplay(false);
  }

  public ngOnInit() {
    var url = this.properties.domain + this.properties.baseLink + this._router.url;
    this.seoService.createLinkForCanonicalURL(url, false);
    this._meta.updateTag({content: url}, "property='og:url'");
    this.subscriptions.push(this._piwikService.trackView(this.properties, "OpenAIRE Connect").subscribe());
    this.subscriptions.push(this.userManagementService.getUserInfo().subscribe(user => {
      this.user = user;
      this.getCommunities();
    },
      error => {
      this.getCommunities();
    }));
    //this.getDivContents();
    this.getPageContents();
  }
  
  ngOnDestroy() {
    this.subscriptions.forEach(subscription => {
      if (subscription instanceof Subscriber) {
        subscription.unsubscribe();
      } else if ((typeof MutationObserver != 'undefined' && subscription instanceof MutationObserver) ||
          (typeof IntersectionObserver != 'undefined' && subscription instanceof IntersectionObserver)) {
        subscription.disconnect();
      }
    });
    this.quickContactService.setDisplay(true);
  }
  
  ngAfterViewInit() {
    if(typeof IntersectionObserver !== "undefined" && typeof MutationObserver !== "undefined") {
      this.createObservers();
    }
  }

  private getPageContents() {
    this.subscriptions.push(this.helper.getPageHelpContents(this.properties, 'connect', this._router.url).subscribe(contents => {
      this.pageContents = contents;
    }));
  }

  private getDivContents() {
    this.subscriptions.push(this.helper.getDivHelpContents(this.properties, 'connect', this._router.url).subscribe(contents => {
      this.divContents = contents;
    }));
  }
  
  createObservers() {
    let options = {
      root: null,
      rootMargin: '200px',
      threshold: 1.0
    };
    let intersectionObserver = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        this.quickContactService.setDisplay(!entry.isIntersecting);
      });
    }, options);
    intersectionObserver.observe(this.contact.nativeElement);
		let mutationObserver = new MutationObserver(entries => {
      entries.forEach(entry => {
        if (entry.attributeName === 'style') {
          let opacities: number[] = this.elements.map(element => +element.nativeElement.style.opacity);
          let active: number = opacities.indexOf(Math.max(...opacities));
          this.elements.forEach((element, index) => {
            if (index === active) {
              element.nativeElement.classList.remove('uk-disabled');
            } else {
              element.nativeElement.classList.add('uk-disabled');
            }
          })
        }
      })
    });
    this.elements.forEach(element => {
      mutationObserver.observe(element.nativeElement, {attributes: true});
    });
    this.subscriptions.push(intersectionObserver);
		this.subscriptions.push(mutationObserver);
  }

  public getCommunities() {
    this.loading = true;
    this.status = this.errorCodes.LOADING;
    this.subscriberErrorMessage = "";

    this.researchCommunities = [];

    this.subscriptions.push(this._communitiesService.getCommunitiesState().subscribe(
      communitiesResults => {
        // console.log("getCommunitiesState", communitiesResults);

        if(!communitiesResults){
          return;
        }
        if(communitiesResults.length == 0) {
          this.status = this.errorCodes.DONE;
          return;
        }
        this.sort(communitiesResults);
        communitiesResults.forEach((community, index) => {
          let showCommunity: boolean = true;
          community.isSubscribed = Session.isSubscribedTo('community', community.communityId, this.user);

          if (community.isPrivate() || community.isRestricted()) {
            showCommunity = false;
          }
          if (showCommunity) {
            this.researchCommunities.push(community);
          }
          this.status = this.errorCodes.DONE;
        });
        this.loading = false;
      },
      error => {
        this.status = this.handleError("Error getting communities", error);
        this.loading = false;
      }
    ));
  }
  
  hasPermission(communityInfo: CommunityInfo) {
    return communityInfo.isPublic() || (communityInfo.isRestricted() && communityInfo.isManager);
  }

  private sort(results: CommunityInfo[]) {
    results.sort((left, right): number => {
      if (!right.date || left.date > right.date) {
        return -1;
      } else if (!left.date || left.date < right.date) {
        return 1;
      } else {
        if (left.title > right.title) {
          return 1;
        } else if (left.title < right.title) {
          return -1;
        } else {
          return 0;
        }
      }
    })
  }

  public quote(param: string): string {
    return StringUtils.quote(param);
  }
  
  private handleError(message: string, error): number {
    var code = "";
    try {
      if (!error.status) {
        var error = error.json();
        code = error.code;
      } else {
        code = error.status;
      }
    }catch(e){}
    console.error("Communities (component): " + message, error);
    return this.errorMessages.getErrorCode(code);
  }
}
