import {
  AfterViewInit,
  ChangeDetectorRef,
  Component,
  ElementRef,
  HostListener,
  Input,
  QueryList, ViewChild,
  ViewChildren
} from '@angular/core';
import {EnvProperties} from "../../utils/properties/env-properties";
import {properties} from "../../../../environments/environment";

@Component({
  selector: 'showIdentifiers',
  template: `
    <!-- <div class="uk-text-muted">Persistent Identifiers</div> -->
    <ng-template #identifiers_template let-modal="modal">
      <ng-container *ngFor="let key of keys let i=index">
<!--        <div [class.uk-margin-bottom]="modal" [class.multi-line-ellipsis]="!modal" [class.lines-2]="keys.length === 1" [class.line-1]="keys.length > 1">-->
          <div class="uk-flex-inline uk-flex-wrap uk-margin-medium-right"
               [class.multi-line-ellipsis]="!modal" [class.lines-2]="keys.length === 1" [class.line-1]="keys.length > 1"
               [class.uk-margin-bottom]="modal">
            <p class="uk-margin-remove">
              <span #content [id]="key" [class.uk-flex]="modal">
                <span class="uk-text-meta uk-text-small" [class.uk-text-uppercase]="key != 're3data'">{{key}}: </span>
                <span [class.uk-margin-small-left]="modal">
                  <ng-container *ngFor="let item of identifiers.get(key) let j=index">
                    <a *ngIf="key == 'doi' || key == 'pmc' || key == 'pmid' || key == 'handle' || key == 're3data' || key == 'swhid' 
                              || key == 'ROR' || key == 'ISNI' || key == 'Wikidata' || key == 'FundRef'"
                       [href]="getUrl(key, item) + item" target="_blank" class="uk-display-inline-block custom-external">
                      {{item}}
                    </a>
                    <ng-container *ngIf="(j !== (identifiers.get(key).length - 1))">, </ng-container>
                  </ng-container>
                </span>
              </span>
            </p>
          </div>
<!--        </div>-->
      </ng-container>
    </ng-template>
    
    <div class="uk-height-max-medium uk-overflow-auto uk-text-small">
      <ng-container *ngTemplateOutlet="identifiers_template; context: { modal: false}"></ng-container>
    </div>
    <div *ngIf="isLarge && showViewAll" class="uk-text-right uk-margin-small-top">
      <a (click)="openIdentifiersModal()" class="view-more-less-link">View all</a>
    </div>

    <modal-alert *ngIf="!isMobile" #identifiersModal>
      <div class="uk-text-small">
        <ng-container *ngTemplateOutlet="identifiers_template; context: { modal: true}"></ng-container>
      </div>
    </modal-alert>

    <fs-modal *ngIf="isMobile" #identifiersModal classTitle="uk-tile-default uk-border-bottom">
      <div class="uk-text-small">
        <ng-container *ngTemplateOutlet="identifiers_template; context: { modal: true}"></ng-container>
      </div>
    </fs-modal>
  `
})
export class ShowIdentifiersComponent implements AfterViewInit {
  @Input() isMobile: boolean = false;
  @Input() identifiers: Map<string, string[]>;
  @Input() showViewAll: boolean = false;
  large: Map<string, boolean> = new Map<string, boolean>();
  properties: EnvProperties = properties;
  @ViewChildren("content", { read: ElementRef }) types: QueryList<ElementRef>;
  @ViewChild('identifiersModal') identifiersModal;

  constructor(private cdr: ChangeDetectorRef) {
  }
  
  @HostListener('window:resize', ['$event'])
  onResize(event) {
    this.checkLarge();
  }
  
  ngAfterViewInit() {
    this.checkLarge();
  }
  
  checkLarge() {
    let overflow = (this.keys.length === 1?42:21);
    if(typeof document !== "undefined") {
      this.keys.forEach(key => {
        let type = this.types.find(type => type.nativeElement.id === key);
        this.large.set(key, type && type.nativeElement.offsetHeight > overflow);
      });
      this.cdr.detectChanges();
    }
  }
  
  get isLarge() {
    for(let key of this.keys) {
      if (this.large.get(key)) {
        return true;
      }
    }
    return false;
  }
  
  public get keys(): string[] {
    return Array.from(this.identifiers.keys()).sort((a: string, b: string) => {
      if (a === 'doi') {
        return -1;
      } else if (b === 'doi') {
        return 1;
      } else {
        return 0;
      }
    });
  }

  public getUrl(key: string, value: string): string {
    if(value.includes("http://") || value.includes("https://")) {
      return "";
    }
   if(key == "doi") {
     return properties.doiURL;
   } else if(key == "pmc") {
     return properties.pmcURL;
   } else if(key == "pmid") {
     return properties.pmidURL;
   } else if(key == "handle") {
     return properties.handleURL;
   } else if(key == "re3data") {
     return properties.r3DataURL;
   } else if(key == "swhid") {
     return properties.swhURL;
   } else if(key == "ROR") {
     return properties.rorURL;
   } else if(key == "ISNI") {
     return properties.isniURL;
   } else if(key == "Wikidata") {
     return properties.wikiDataURL;
   } else if(key == "FundRef") {
     return properties.fundRefURL;
   }
  }

  public openIdentifiersModal() {
    if(this.isMobile) {
      this.identifiersModal.okButton = false;
      this.identifiersModal.title = "Persistent Identifiers";
      this.identifiersModal.open();
    } else {
      this.identifiersModal.cancelButton = false;
      this.identifiersModal.okButton = false;
      this.identifiersModal.alertTitle = "Persistent Identifiers";
      this.identifiersModal.open();
    }
  }
}
