import {Component, ViewChild} 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 {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 {RefineFieldResultsService} from "../openaireLibrary/services/refineFieldResults.service";
import {NumberUtils} from "../openaireLibrary/utils/number-utils.class";
import {SearchResearchResultsService} from "../openaireLibrary/services/searchResearchResults.service";
import {animate, state, style, transition, trigger} from "@angular/animations";
import {StakeholderService} from "../openaireLibrary/monitor/services/stakeholder.service";
import {LocalStorageService} from "../openaireLibrary/services/localStorage.service";
import {Stakeholder, Visibility} from "../openaireLibrary/monitor/entities/stakeholder";
import {Session, User} from "../openaireLibrary/login/utils/helper.class";
import {UserManagementService} from "../openaireLibrary/services/user-management.service";
import {properties} from "../../environments/environment";
import {Subscriber} from "rxjs";

@Component({
  selector: 'home',
  templateUrl: 'home.component.html',
  styleUrls: ['home.component.css'],
  animations: [
    trigger('1', [
      state('1', style({
        opacity: 1
      })),
      transition('* => *', [
        animate('0.3s')
      ])
    ]),
    trigger('2', [
      state('2', style({
        opacity: 1
      })),
      transition('* => *', [
        animate('0.3s')
      ])
    ]),
    trigger('3', [
      state('3', style({
        opacity: 1
      })),
      transition('* => *', [
        animate('0.3s')
      ])
    ])
  ]
})
export class HomeComponent {
  public pageTitle = "OpenAIRE | Monitor";
  public stakeholders: Stakeholder[] = [];
  public selected: Stakeholder = null;
  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 = null;
  
  public publicationsSize: any = null;
  public datasetsSize: any = null;
  public softwareSize: any = null;
  public otherSize: any = null;
  public fundersSize: any = null;
  subscriptions = [];

  public state = 1;
  private timeouts: any[] = [];
  @ViewChild('AlertModal') modal;
  public directLink: boolean = true;
  private user: User;
  visibilityIcon: Map<Visibility, string> = new Map<Visibility, string> ([
    ["PUBLIC", 'earth'],
    ["PRIVATE", 'lock'],
    ["RESTRICTED", 'group']
  ]);
  
  constructor(
    private route: ActivatedRoute,
    private _router: Router,
    private _meta: Meta,
    private _title: Title,
    private _piwikService: PiwikService,
    private _stakeholderService: StakeholderService,
    private localStorageService: LocalStorageService,
    private userManagementService: UserManagementService,
    private helper: HelperService,
    private seoService: SEOService,
    private _refineFieldResultsService: RefineFieldResultsService, private _searchResearchResultsService: SearchResearchResultsService) {
    
    
    var description = "OpenAIRE - Monitor, A new era of monitoring research. Open data. Open methodologies. Work together with us to view, understand and visualize research statistics and indicators. ";
    var title = "OpenAIRE - Monitor";
    
    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 Monitor", this.properties.piwikSiteId).subscribe());
    }
    this.getNumbers();
    this.getStakeholders();
    // this.createGifs();
    //this.getDivContents();
    // this.getPageContents();
    this.subscriptions.push(this.localStorageService.get().subscribe(value => {
      this.directLink = value;
    }));
    this.subscriptions.push(this.userManagementService.getUserInfo().subscribe(user => {
      this.user = user;
    }));

    if(typeof document != "undefined") {
      this.startAnimation();
    }
  }
  
  public startAnimation(state = 1) {
    this.clearTimeouts();
    this.state = state;
    this.timeouts.push(setTimeout(() => {
      if (this.state < 3) {
        this.startAnimation(this.state + 1);
      } else {
        this.startAnimation();
      }
    }, 6000));
  }
  
  private clearTimeouts() {
    this.timeouts.forEach(timeout => {
      clearTimeout(timeout);
    });
  }
  
  private getPageContents() {
    this.subscriptions.push(this.helper.getPageHelpContents(this.properties, 'monitor', this._router.url).subscribe(contents => {
      this.pageContents = contents;
    }));
  }
  
  private getDivContents() {
    this.subscriptions.push(this.helper.getDivHelpContents(this.properties, 'monitor', this._router.url).subscribe(contents => {
      this.divContents = contents;
    }));
  }
  
  public get stakeholdersNumber(): number {
    if(this.type === null) {
      return this.stakeholders.length;
    } else {
      return this.stakeholders.filter(stakeholder => stakeholder.type === this.type).length;
    }
  }
  
  getNumbers() {
    this.subscriptions.push(this._refineFieldResultsService.getRefineFieldsResultsByEntityName(["funder"], "project", this.properties).subscribe(
      data => {
        if (data[1].length > 0 && data[1][0].filterId == "funder" && data[1][0].values) {
          this.fundersSize = NumberUtils.roundNumber(data[1][0].values.length);
        }
      },
      err => {
        //console.log(err);
        this.handleError("Error getting 'funder' field results of projects", err);
      }));

    this.subscriptions.push(this._searchResearchResultsService.numOfSearchResults("publication", "", this.properties).subscribe(
      data => {
        if (data && data > 0) {
          this.publicationsSize = NumberUtils.roundNumber(data);
        }
      },
      err => {
        //console.log(err);
        this.handleError("Error getting number of publications", err);
      }
    ));

    this.subscriptions.push(this._searchResearchResultsService.numOfSearchResults("dataset", "", this.properties).subscribe(
      data => {
        if (data && data > 0) {
          this.datasetsSize = NumberUtils.roundNumber(data);
        }
      },
      err => {
        //console.log(err);
        this.handleError("Error getting number of research data", err);
      }
    ));

    this.subscriptions.push(this._searchResearchResultsService.numOfSearchResults("software", "", this.properties).subscribe(
      data => {
        if (data && data > 0) {
          this.softwareSize = NumberUtils.roundNumber(data);
        }
      },
      err => {
        this.handleError("Error getting number of software data", err);
      }
    ));

    this.subscriptions.push(this._searchResearchResultsService.numOfSearchResults("other", "", this.properties).subscribe(
      data => {
        if (data && data > 0) {
          this.otherSize = NumberUtils.roundNumber(data);
        }
      },
      err => {
        this.handleError("Error getting number of software data", err);
      }
    ));
    
    
  }
  
  public getStakeholders() {
    this.loading = true;
    this.status = this.errorCodes.LOADING;
    this.subscriberErrorMessage = "";
    this.subscriptions.push(this._stakeholderService.getStakeholders(this.properties.monitorServiceAPIURL).subscribe(
      stakeholders => {
        if (!stakeholders || stakeholders.length == 0) {
          this.status = this.errorCodes.NONE;
        } else {
					// compare function for alphabetical order based on the 'name' property
					function compare (a, b) {
						if(a.name < b.name) {
							return -1;
						}
						if(a.name > b.name) {
							return 1;
						}
						return 0;
					}
					let publicStakeholders = [];
					let restrictedStakeholders = [];
					stakeholders.forEach(stakeholder => {
						if(stakeholder.visibility == "PUBLIC") {
							publicStakeholders.push(stakeholder);
						} else {
							restrictedStakeholders.push(stakeholder);
						}
					});
					// actual sorting of the arrays
					publicStakeholders.sort(compare);
					restrictedStakeholders.sort(compare);
					// joining the two arrays again
					this.stakeholders = publicStakeholders.concat(restrictedStakeholders);
        }
        this.loading = false;
      },
      error => {
        this.status = this.handleError("Error getting funders", error);
        this.loading = false;
      }
    ));
  }
  
  private isManager(stakeholder: Stakeholder) {
    return Session.isPortalAdministrator(this.user) || Session.isMonitorCurator(this.user) || Session.isManager(stakeholder.type, stakeholder.alias, this.user);
  }
  
  private isMember(stakeholder: Stakeholder) {
    return Session.isMember(stakeholder.type, stakeholder.alias, this.user);
  }
  
  public confirmModalOpen(result: Stakeholder) {
    this.selected = result;
    this.modal.cancelButton = true;
    this.modal.okButton = true;
    this.modal.alertTitle = 'You are going to visit ' + result.name + ' Monitor Dashboard';
    this.modal.alertMessage = false;
    this.modal.okButtonLeft = false;
    this.modal.okButtonText = 'Yes';
    this.modal.cancelButtonText = 'No';
    this.modal.choice = true;
    this.modal.open();
  }
  
  public getStakeholderPageUrl(stakeholder: Stakeholder) {
    return this.properties.domain + this.properties.baseLink + '/dashboard/' + stakeholder.alias;
  }
  
  public goToPage(data: any) {
    if (data.value == true) {
      let url = this.getStakeholderPageUrl(this.selected);
      this.localStorageService.setCommunityDirectLink(data.choice);
      window.open(url, '_blank');
    }
  }
  
  public quote(param: string): string {
    return StringUtils.quote(param);
  }

  ngOnDestroy() {
    this.subscriptions.forEach(subscription => {
      if (subscription instanceof Subscriber) {
        subscription.unsubscribe();
      }
    });
    this.clearTimeouts();
  }
  
  hasPermission(stakeholder: Stakeholder) {
    return stakeholder.visibility === "PUBLIC" || this.isManager(stakeholder) || this.isMember(stakeholder);
  }
  
  private handleError(message: string, error): number {
    var code = "";
    if (!error.status) {
      var error = error.json();
      code = error.code;
    } else {
      code = error.status;
    }
    
    console.error("Home Component: " + message, error);
    
    return this.errorMessages.getErrorCode(code);
  }
}
