import {
  AfterContentChecked,
  AfterViewInit,
  ChangeDetectorRef,
  Component,
  Inject,
  OnDestroy,
  OnInit,
  PLATFORM_ID,
  ViewChild
} from "@angular/core";
import {Subscription} from "rxjs";
import {Meta, Title} from "@angular/platform-browser";
import {ActivatedRoute, Router} from "@angular/router";
import {OpenaireEntities} from "../../utils/properties/searchFields";
import {SEOService} from "../../sharedComponents/SEO/SEO.service";
import {properties} from "../../../../environments/environment";
import {Breadcrumb} from "../../utils/breadcrumbs/breadcrumbs.component";
import {HelperService} from "../../utils/helper/helper.service";
import {LayoutService} from "../../dashboard/sharedComponents/sidebar/layout.service";
import {isPlatformServer} from "@angular/common";


declare var ResizeObserver;

@Component({
  selector: 'terminology',
  template: `
		<div *ngIf="!isMobile" class="uk-visible@m">
			<div class="uk-background-muted">
				<div class="uk-container uk-container-large uk-section uk-section-small">
					<div class="uk-padding-small uk-padding-remove-horizontal">
						<breadcrumbs [breadcrumbs]="breadcrumbs"></breadcrumbs>
					</div>
					<div class="uk-text-center" uk-scrollspy-class>
						<h1 class="uk-margin-medium-top uk-margin-medium-bottom">Terminology and <br> construction<span
								class="uk-text-primary">.</span></h1>
					</div>
				</div>
			</div>
			<div *ngIf="divContents" uk-scrollspy="target: [uk-scrollspy-class]; cls: uk-animation-fade; delay: 250">
				<div id="graph_element" #graph_element class="uk-blur-background uk-padding-xsmall" uk-sticky="end: true"
						 [attr.offset]="graph_offset">
					<div class="uk-container uk-container-large">
            <a href="https://graph.openaire.eu" target="_blank" class="uk-width-1-1 uk-width-auto@m">
              <img src="assets/common-assets/openaire-badge-1.png" alt="Powered by OpenAIRE graph" style="height: 17px;">
            </a>
					</div>
				</div>
				<div class="uk-section uk-container uk-container-large" uk-scrollspy-class>
					<div id="parentContainer" class="uk-grid uk-grid-large" uk-grid>
						<div class="uk-width-medium uk-margin-top">
							<div class="uk-sticky" uk-sticky="end: !#parentContainer; offset: 100;">
								<slider-tabs type="scrollable" position="left">
									<slider-tab tabId="entities" tabTitle="1. Entities"></slider-tab>
									<slider-tab tabId="inherited-and-inferred-attributes" tabTitle="2. Inherited and Inferred Attributes"></slider-tab>
									<slider-tab tabId="constructed-attributes" tabTitle="3. Constructed Attributes"></slider-tab>
								</slider-tabs>
							</div>
						</div>
						<div class="uk-width-expand uk-margin-top">
							<div id="entities" class="uk-margin-large-bottom">
								<helper [texts]="divContents['entities']"></helper>
							</div>
							<div id="inherited-and-inferred-attributes" class="uk-margin-large-bottom">
								<helper [texts]="divContents['inherited-and-inferred-attributes']"></helper>
							</div>
							<div id="constructed-attributes" class="uk-margin-large-bottom">
								<helper [texts]="divContents['constructed-attributes']"></helper>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<div *ngIf="isMobile || isServer" class="uk-hidden@m">
			<div class="uk-background-muted">
				<div class="uk-container uk-container-large">
					<div class="uk-text-center" uk-scrollspy-class>
						<h1 class="uk-heading-small uk-margin-medium-top uk-margin-medium-bottom">Terminology and <br> construction<span
							class="uk-text-primary">.</span></h1>
					</div>
				</div>
			</div>
			<div *ngIf="divContents" uk-scrollspy="target: [uk-scrollspy-class]; cls: uk-animation-fade; delay: 250">
				<div id="graph_element" #graph_element class="uk-blur-background uk-padding-xsmall" uk-sticky="end: true"
					[attr.offset]="graph_offset">
					<div class="uk-container uk-container-large uk-text-xsmall uk-text-right">
            <a href="https://graph.openaire.eu" target="_blank" class="uk-width-1-1 uk-width-auto@m">
              <img src="assets/common-assets/openaire-badge-1.png" alt="Powered by OpenAIRE graph" style="height: 17px;">
            </a>
					</div>
				</div>
				<div>
					<div class="uk-sticky uk-background-default uk-padding-small uk-padding-remove-right" uk-sticky>
						<slider-tabs type="scrollable" position="horizontal">
							<slider-tab tabId="entities_m" tabTitle="1. Entities"></slider-tab>
							<slider-tab tabId="inherited-and-inferred-attributes_m"
													tabTitle="2. Inherited and Inferred Attributes"></slider-tab>
							<slider-tab tabId="constructed-attributes_m" tabTitle="3. Constructed Attributes"></slider-tab>
						</slider-tabs>
					</div>
				</div>
				<div class="uk-container uk-container-large uk-section uk-section-small uk-text-break">
					<div id="entities_m" class="uk-margin-xlarge-bottom">
						<helper [texts]="divContents['entities']"></helper>
					</div>
					<div id="inherited-and-inferred-attributes_m" class="uk-margin-xlarge-bottom">
						<helper [texts]="divContents['inherited-and-inferred-attributes']"></helper>
					</div>
					<div id="constructed-attributes_m" class="uk-margin-xlarge-bottom">
						<helper [texts]="divContents['constructed-attributes']"></helper>
					</div>
				</div>
			</div>
		</div>
  `,
  styleUrls: ['terminology.component.less']
})
export class TerminologyComponent implements OnInit, OnDestroy, AfterViewInit, AfterContentChecked {
  public tab: 'entities' | 'attributes' = 'entities';
  private subscriptions: any[] = [];
  public openaireEntities = OpenaireEntities;
  public breadcrumbs: Breadcrumb[] = [{name: 'home', route: '/'}, {name: 'Resources - Terminology and construction', keepFormat: true}];
  public graph_offset: number = 0;
  public graph_height: number = 0;
  @ViewChild("graph_element") graph_element;
  public contentSections: string[] = ['entities', 'inherited-and-inferred-attributes', 'constructed-attributes'];
  public activeSection: string;
  public properties = properties;
  public divContents: any;
	isMobile: boolean = false;
	isServer: boolean;
  
  constructor(private seoService: SEOService,
              private meta: Meta,
              private router: Router,
              private route: ActivatedRoute,
              private title: Title,
              private cdr: ChangeDetectorRef,
              private helper: HelperService,
							private layoutService: LayoutService,
							@Inject(PLATFORM_ID) private platform: any) {
		this.isServer = isPlatformServer(this.platform);
  }
  
  ngOnInit() {
    this.subscriptions.push(this.route.params.subscribe(params => {
      const description = "Monitor | Terminology and construction";
      const title = "Monitor | Terminology and construction";
      this.metaTags(title, description);
      this.breadcrumbs[0].route = '/' + (params['stakeholder']?params['stakeholder']:'');
      this.breadcrumbs[0].name = (params['stakeholder']?'dashboard':'home');
    }));
    this.subscriptions.push(this.route.fragment.subscribe(fragment => {
      if(fragment) {
        this.activeSection = fragment;
      } else {
        this.activeSection = 'entities';
      }
    }));
		this.layoutService.isMobile.subscribe(isMobile => {
			this.isMobile = isMobile;
			this.cdr.detectChanges();
		});
    this.getDivContents();
  }
  
  ngAfterViewInit() {
    if (typeof document !== 'undefined') {
      if(this.graph_element) {
        this.observeGraphElement();
      }
    }
  }
  
  ngAfterContentChecked() {
    if(this.graph_element && typeof document !== 'undefined') {
      this.graph_offset = this.calcGraphOffset(this.graph_element.nativeElement);
    }
  }
  
  ngOnDestroy() {
    this.subscriptions.forEach(subscription => {
      if (subscription instanceof Subscription) {
        subscription.unsubscribe();
      } else if(typeof ResizeObserver != 'undefined' && subscription instanceof ResizeObserver) {
        subscription.disconnect();
      }
    });
  }
  
  private getDivContents() {
    this.subscriptions.push(this.helper.getDivHelpContents(this.properties, 'monitor', '/methodology/terminology').subscribe(contents => {
      this.divContents = contents;
    }));
  }
  
  public observeGraphElement() {
    let resizeObs = new ResizeObserver(entries => {
      entries.forEach(entry => {
        setTimeout(() => {
          this.graph_offset = this.calcGraphOffset(entry.target);
          this.cdr.detectChanges();
        });
      })
    });
    this.subscriptions.push(resizeObs);
    resizeObs.observe(this.graph_element.nativeElement);
  }
  
  calcGraphOffset(element) {
    this.graph_height = element.offsetHeight;
    return window.innerHeight-this.graph_height;
  }
  
  metaTags(title, description) {
    const url = properties.domain + properties.baseLink + this.router.url;
    this.seoService.createLinkForCanonicalURL(url, false);
    this.meta.updateTag({content: url}, "property='og:url'");
    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);
  }
}
