import {Component} 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";

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

export class CommunitiesComponent {
  private subscriptions = [];

  public pageTitle = "OpenAIRE"
  public researchCommunities: CommunityInfo[] = [];
  public gifs: { "gif": string, "header": string, "text" }[] = [];
  public pageContents = null;
  public divContents = null;
  // Message variables
  public status: number;
  public loading: boolean = true;
  public subscriberErrorMessage: string = "";
  public errorCodes: ErrorCodes;
  private errorMessages: ErrorMessagesComponent;

  properties: EnvProperties;
  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) {

    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;
  }

  public ngOnInit() {
    this.properties = properties;
    var url = this.properties.domain + this.properties.baseLink + this._router.url;
    this.seoService.createLinkForCanonicalURL(url, false);
    this._meta.updateTag({content: url}, "property='og:url'");
    if (this.properties.enablePiwikTrack && (typeof document !== 'undefined')) {
      this.subscriptions.push(this._piwikService.trackView(this.properties, "OpenAIRE Connect", this.properties.piwikSiteId).subscribe());
    }
    this.getCommunities();
    this.createGifs();
    //this.getDivContents();
    this.getPageContents();
  }

  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;
    }));
  }

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

    this.researchCommunities = [];

    this.subscriptions.push(this._communitiesService.getCommunitiesState().subscribe(
      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;
          if (community['status'] == "hidden" || community['status'] == "manager") {
            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;
      }
    ));
  }

  private createGifs() {
    this.gifs.push({
      gif: "assets/connect-assets/home/gifs/deposit.gif",
      header: "Find a repository to deposit your research outcome",
      text: "This is OpenAIRE’s key service for research communities, both established and emerging ones. Our service helps you reach out and engage all your researchers to practice open science out-of-the-box."
    });
    this.gifs.push({
      gif: "assets/connect-assets/home/gifs/link.gif",
      header: "Link your research output with your community, funding, and other research products",
      text: "This is OpenAIRE’s key service for research communities, both established and emerging ones. Our service helps you reach out and engage all your researchers to practice open science out-of-the-box."
    });
    this.gifs.push({
      gif: "assets/connect-assets/home/gifs/overview.gif",
      header: "View community's overview at a glance",
      text: "This is OpenAIRE’s key service for research communities, both established and emerging ones. Our service helps you reach out and engage all your researchers to practice open science out-of-the-box."
    });
    this.gifs.push({
      gif: "assets/connect-assets/home/gifs/results.gif",
      header: "Search & browse your community's research products. ",
      text: "This is OpenAIRE’s key service for research communities, both established and emerging ones. Our service helps you reach out and engage all your researchers to practice open science out-of-the-box."
    });
    this.gifs.push({
      gif: "assets/connect-assets/home/gifs/graph-analysis.gif",
      header: "View statistics for your community's research products.",
      text: "This is OpenAIRE’s key service for research communities, both established and emerging ones. Our service helps you reach out and engage all your researchers to practice open science out-of-the-box."
    });
  }

  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);
  }

  ngOnDestroy() {
    this.subscriptions.forEach(subscription => {
      if (subscription instanceof Subscriber) {
        subscription.unsubscribe();
      }
    });
  }

  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);
  }
}
