import {Component, OnDestroy, OnInit} from '@angular/core';
import {Subscription} from 'rxjs';
import {ActivatedRoute, Router} from '@angular/router';
import {Location} from '@angular/common';
import {Meta, Title} from '@angular/platform-browser';
import {ConfigurationService} from '../openaireLibrary/utils/configuration/configuration.service';
import {EnvProperties} from '../openaireLibrary/utils/properties/env-properties';
import {PiwikService} from '../openaireLibrary/utils/piwik/piwik.service';
import {SEOService} from '../openaireLibrary/sharedComponents/SEO/SEO.service';
import {properties} from '../../environments/environment';
import {portals} from './portals';
import {Filter} from '../openaireLibrary/searchPages/searchUtils/searchHelperClasses.class';
import {RouterHelper} from '../openaireLibrary/utils/routerHelper.class';

@Component({
  selector: 'home',
  templateUrl: 'home.component.html',
  styleUrls: ['home.component.css']
})
export class HomeComponent implements OnInit, OnDestroy {
  public pageTitle = 'OpenAIRE - Research Graph';
  public portals: any[] = portals;
  public state: number = 0;
  public properties: EnvProperties = properties;
  public selectedEntity = 'all';
  public url: string;
  public routerHelper: RouterHelper = new RouterHelper();
  public resultTypes: Filter = {
    values: [
      {name: 'Publications', id: 'publications', selected: true, number: 0},
      {name: "Research data", id: "datasets", selected: true, number: 0},
      {name: "Software", id: "software", selected: true, number: 0},
      {name: "Other research products", id: "other", selected: true, number: 0}
    ],
    filterId: 'type',
    countSelectedValues: 0,
    filterType: 'checkbox',
    originalFilterId: '',
    valueIsExact: true,
    title: 'Result Types',
    filterOperator: 'or'
  };
  public resultsQuickFilter: { filter: Filter, selected: boolean, filterId: string, value: string } = {
    filter: null,
    selected: true,
    filterId: 'resultbestaccessright',
    value: 'Open Access'
  };
  public keyword: string = '';
  private timeouts: any[] = [];
  private subs: Subscription[] = [];
  
  constructor(
    private route: ActivatedRoute,
    private _router: Router,
    private location: Location, private _piwikService: PiwikService,
    private config: ConfigurationService, private _meta: Meta, private _title: Title, private seoService: SEOService
  ) {
    
    let description = 'OpenAIRE Research Graph is an open resource that aggregates a collection of research data properties (metadata, links) available within the OpenAIRE Open Science infrastructure for funders, organizations, researchers, research communities and publishers to interlink information by using a semantic graph database approach.';
    
    this._title.setTitle(this.pageTitle);
    this._meta.updateTag({content: description}, 'name="description"');
    this._meta.updateTag({content: description}, 'property="og:description"');
    this._meta.updateTag({content: this.pageTitle}, 'property="og:title"');
  }
  
  public ngOnInit() {
    if (this.properties) {
      let 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.subs.push(this._piwikService.trackView(this.properties, this.pageTitle).subscribe());
      }
      this.animation();
    }
  }
  
  public ngOnDestroy() {
    this.subs.forEach(sub => {
      if(sub instanceof Subscription) {
        sub.unsubscribe();
      }
    });
    this.clearTimeouts();
  }
  
  private animation() {
    this.timeouts.push(setTimeout(() => {
      this.animation();
      if (this.state === (this.portals.length - 1)) {
        this.state = 0;
      } else {
        this.state++;
      }
    }, 4000));
  }
  
  entityChanged($event) {
    this.selectedEntity = $event.entity;
    this.url = $event.simpleUrl;
  }
  
  private changeSlide(slide: number) {
    this.clearTimeouts();
    this.state = slide;
    this.animation();
  }
  
  private clearTimeouts() {
    this.timeouts.forEach(timeout => {
      clearTimeout(timeout);
    });
    this.state = 0;
  }
  
  goTo() {
    let url = 'https://explore.openaire.eu' + this.url;
    let parameterNames = [];
    let parameterValues = [];
    if (this.selectedEntity == 'result') {
      if (this.resultTypes) {
        let values = [];
        for (let value of this.resultTypes.values) {
          if (value.selected) {
            values.push(value.id);
          }
        }
        if (values.length > 0 && values.length != 4) {
          parameterNames.push('type');
          parameterValues.push(values.join(','));
        }
        if (this.resultsQuickFilter && this.resultsQuickFilter.selected) {
          parameterNames.push(this.resultsQuickFilter.filterId);
          parameterValues.push('"'+ encodeURIComponent(this.resultsQuickFilter.value)+'"');
        }
      }
    } else if (this.selectedEntity == 'all') {
      if (this.resultsQuickFilter && this.resultsQuickFilter.selected) {
        parameterNames.push(this.resultsQuickFilter.filterId);
        parameterValues.push('"'+ encodeURIComponent(this.resultsQuickFilter.value)+'"');
      }
    }
    if (this.keyword.length > 0) {
      parameterNames.push('fv0');
      parameterValues.push(this.keyword);
      parameterNames.push('f0');
      parameterValues.push('q');
    }
    window.open(url + this.routerHelper.createQueryParamsString(parameterNames, parameterValues), '_blank').focus();
  }
}
