import {
  ChangeDetectorRef,
  Component,
  ElementRef, EventEmitter,
  HostListener,
  Input, Output,
  QueryList,
  ViewChild,
  ViewChildren
} from '@angular/core';
import {properties} from "../../../../environments/environment";

@Component({
  selector: 'showSubjects',
  template: `     
    <ng-container *ngIf="properties.environment == 'production' && !viewAllSubjects && ((classifiedSubjects && classifiedSubjects.size > 0) || (eoscSubjects && eoscSubjects.length > 0))">
      <div *ngIf="!viewAllClassifiedSubjects" class="uk-text-meta">
        Subjects by Vocabulary
      </div>
      <ng-container *ngTemplateOutlet="subjects_by_vocabulary_template; context: {customClasses: (isMobile && viewAllClassifiedSubjects) ? '' : 'multi-line-ellipsis lines-2', id: 'content'}"></ng-container>
      <ng-container *ngIf="eoscSubjects && eoscSubjects.length > 0"><ng-container *ngTemplateOutlet="eosc_subjects_template"></ng-container></ng-container>
      <div *ngIf="isClassifiedLarge && !viewAllClassifiedSubjects" class="uk-text-right">
        <a (click)="viewAllSubjectsByVocabularyClicked()" class="view-more-less-link">View all</a>
      </div>
    </ng-container>
    
    <ng-container  *ngIf="!viewAllClassifiedSubjects && ((subjects && subjects.length > 0) || (otherSubjects && otherSubjects.size > 0))">
      <div *ngIf="!viewAllSubjects" class="uk-text-meta uk-margin-small-bottom" 
           [class.uk-margin-medium-top]="properties.environment == 'production' && ((classifiedSubjects && classifiedSubjects.size > 0) || (eoscSubjects && eoscSubjects.length > 0))">
        Keywords
      </div>
      <ng-container *ngTemplateOutlet="subjects_template; context: {customClasses: (isMobile && viewAllSubjects) ? '' : 'multi-line-ellipsis lines-2', id: 'content'}"></ng-container>
      <div *ngIf="isLarge && !viewAllSubjects" class="uk-text-right uk-margin-small-top">
        <a (click)="viewAllSubjectsClicked()" class="view-more-less-link">View all</a>
      </div>
    </ng-container>
    
    <ng-container *ngIf="properties.environment != 'production' && !viewAllSubjects && ((eoscSubjects && eoscSubjects.length > 0))">
      <div class="uk-text-meta uk-margin-small-bottom"
           [class.uk-margin-medium-top]="(subjects && subjects.length > 0) || (otherSubjects && otherSubjects.size > 0)">
        EOSC Subjects
      </div>
      <div *ngIf="eoscSubjects && eoscSubjects.length > 0">
        <ng-container *ngTemplateOutlet="eosc_subjects_template; context: {id: 'content'}"></ng-container>
      </div>
    </ng-container>

    <ng-template #subjects_template let-customClasses="customClasses" let-id="id">
      <div class="uk-text-break" [ngClass]="customClasses">
        <p *ngIf="subjects && subjects.length > 0"><span #content [id]="id">{{subjects.join(', ')}}</span></p>
<!--        <span *ngIf="(subjects && subjects.length > 0) && (otherSubjects && otherSubjects.size > 0)">, </span>-->
<!--        <span *ngIf="otherSubjects && otherSubjects.size > 0">-->
<!--            <span *ngFor="let key of getKeys(otherSubjects); let i=index">-->
<!--              <span *ngIf="otherSubjects.get(key).length > 0">-->
<!--                <span>{{otherSubjects.get(key).join(', ')}}</span>-->
<!--                <span *ngIf="i < (otherSubjects.size - 1)">, </span>-->
<!--              </span>-->
<!--            </span>-->
<!--          </span>-->
      </div>
    </ng-template>
    
    <modal-alert #subjectsModal *ngIf="!isMobile && ((subjects && subjects.length > 0) || (otherSubjects && otherSubjects.size > 0))">
      <div class="uk-text-small">
        <ng-container *ngTemplateOutlet="subjects_template"></ng-container>
      </div>
    </modal-alert>

    <ng-template #subjects_by_vocabulary_template let-customClasses="customClasses" let-id="id">
      <div *ngFor="let key of getKeys(classifiedSubjects) let i=index"
           class="uk-flex-wrap uk-margin-medium-right"
           [ngClass]="customClasses">
        <p class="uk-flex uk-flex-middle uk-margin-bottom">
          <span  #classifiedContent [id]="id+'_'+key">
            <span class="uk-margin-small-top uk-display-inline-block">
              <span uk-icon="tag"></span>
              <span class="uk-text-bold uk-margin-small-right"> {{key}}: </span>
            </span>
            <span *ngFor="let subject of classifiedSubjects.get(key); let j=index" class="uk-margin-small-top uk-width-auto uk-display-inline-block">
              <span class="uk-border-rounded uk-label uk-label-small uk-label-primary uk-text-truncate uk-margin-small-right">
                {{subject}}
              </span>
            </span>
          </span>
        </p>
      </div>
    </ng-template>

    <ng-template #eosc_subjects_template let-customClasses="customClasses" let-id="id">
      <div class="uk-flex-wrap uk-margin-medium-right"
           [ngClass]="customClasses">
        <p *ngIf="properties.environment == 'production'" class="uk-flex uk-flex-middle uk-margin-bottom">
          <span  #classifiedContent [id]="id+'_eosc'">
            <span class="uk-margin-small-top uk-display-inline-block">
              <span uk-icon="tag"></span>
              <span class="uk-text-bold uk-margin-small-right"> EOSC: </span>
            </span>
            <span *ngFor="let subject of eoscSubjects; let j=index" class="uk-margin-small-top uk-width-auto uk-display-inline-block">
              <span class="uk-border-rounded uk-label uk-label-small uk-label-primary uk-text-truncate uk-margin-small-right">
                {{subject.value}}
              </span>
            </span>
          </span>
        </p>

        <p *ngIf="properties.environment != 'production' && eoscSubjects && eoscSubjects.length > 0">
          <span #classifiedContent [id]="id+'_eosc'">{{getValue(eoscSubjects).join(', ')}}</span>
        </p>
      </div>
    </ng-template>
    
    <modal-alert #subjectsByVocabularyModal *ngIf="!isMobile && ((classifiedSubjects && classifiedSubjects.size > 0) || (eoscSubjects && eoscSubjects.length > 0))" large="true">
      <div class="uk-text-small">
        <ng-container *ngTemplateOutlet="subjects_by_vocabulary_template"></ng-container>
        <ng-container *ngIf="eoscSubjects && eoscSubjects.length > 0"><ng-container *ngTemplateOutlet="eosc_subjects_template; context: {id: 'content'}"></ng-container></ng-container>
      </div>
    </modal-alert>
  `
})

export class ShowSubjectsComponent {
  @Input() isMobile: boolean = false;
  @Input() subjects: string[];
  @Input() otherSubjects: Map<string, string[]>;
  @Input() classifiedSubjects: Map<string, string[]>;
  @Input() eoscSubjects: any[];
  isLarge: boolean = false;
  isClassifiedLarge: boolean = false;
  @Input() viewAllSubjects: boolean = false;
  @Input() viewAllClassifiedSubjects: boolean = false;
  @Output() viewAllClicked  = new EventEmitter();
  properties = properties;
  specialSubjects = [];
  @ViewChildren("content", { read: ElementRef }) content: QueryList<ElementRef>;
  @ViewChildren("classifiedContent", { read: ElementRef }) classifiedContent: QueryList<ElementRef>;
  @ViewChild('subjectsModal') subjectsModal;
  @ViewChild('subjectsByVocabularyModal') subjectsByVocabularyModal;

  @HostListener('window:resize', ['$event'])
  onResize(event) {
    this.checkLarge();
    this.checkLargeClassified();
  }

  constructor(private cdr: ChangeDetectorRef) {
    if(properties.dashboard == "explore") {
      this.specialSubjects = [
        // "Physics::Optics",
        // "Astrophysics::Cosmology and Extragalactic Astrophysics",
        // "Computer Science::Information Theory",
        // "Physics::Accelerator Physics",
        // "Condensed Matter::Superconductivity",
        "Physics::Atomic Physics",
        // "Computer Science::Robotics",
        // "Computer Science::Computer Science and Game Theory",
        // "Computer Science::Neural and Evolutionary Computation",
        "Mathematics::Combinatorics",
        // "Mathematics::Probability",
        // "Computer Science::Operating Systems",
        // "lcsh:Medicine",
        // "lcsh:Science",
        // "lcsh:Biology (General)",
        // "lcsh:Chemistry",
        // "lcsh:Engineering (General). Civil engineering (General)",
        // "lcsh:Technology"
      ];
    }
  }

  ngOnInit() {
  }

  ngAfterViewInit() {
    setTimeout(() => {
      this.checkLarge();
      this.checkLargeClassified();
    })
  }

  checkLarge() {
    let overflow = 42;
    if(typeof document !== "undefined" && this.content) {
      let element = this.content.find(content => content.nativeElement.id === "content");
      this.isLarge = (element && element.nativeElement.offsetHeight > overflow);
    }
  }

  checkLargeClassified() {
    this.isClassifiedLarge = false;

    let overflow = 69; // 2 * label height (27): 54 + grid margin: 15
    if(typeof document !== "undefined" && this.classifiedSubjects && this.classifiedContent) {
      this.getKeys(this.classifiedSubjects).forEach(key => {
        let tag = this.classifiedContent.find(tag => tag.nativeElement.id === "content_"+key);
        if(tag && tag.nativeElement.offsetHeight > overflow) {
          this.isClassifiedLarge = true;
        }
      });
    }
    if(typeof document !== "undefined" && this.eoscSubjects && this.classifiedContent) {
      let tag = this.classifiedContent.find(tag => tag.nativeElement.id === "content_eosc");
      if(tag && tag.nativeElement.offsetHeight > overflow) {
        this.isClassifiedLarge = true;
      }
    }
  }

  public getKeys(map) {
    return map ? Array.from(map.keys()) : [];
  }
  getSubjectParameter(param){
    return {'f0':'resultsubject','fv0':'"' +(param)+'"', size:50};
  }

  public openSubjectsModal() {
    this.subjectsModal.cancelButton = false;
    this.subjectsModal.okButton = false;
    this.subjectsModal.alertTitle = "Subjects";
    this.subjectsModal.open();
  }

  public openSubjectsByVocabularyModal() {
    this.subjectsByVocabularyModal.cancelButton = false;
    this.subjectsByVocabularyModal.okButton = false;
    this.subjectsByVocabularyModal.alertTitle = "Subjects by Vocabulary";
    this.subjectsByVocabularyModal.open();
  }

  public viewAllSubjectsClicked() {
    if(this.isMobile) {
      this.viewAllSubjects = true;
      this.viewAllClicked.emit({
        subtitle: 'Keywords',
        id: 'subjects'
      });
    } else {
      this.openSubjectsModal();
    }
  }

  public viewAllSubjectsByVocabularyClicked() {
    if(this.isMobile) {
      this.viewAllClassifiedSubjects = true;
      this.viewAllClicked.emit({
        subtitle: 'Subjects by Vocabulary',
        id: 'classifiedSubjects'
      });
    } else {
      this.openSubjectsByVocabularyModal();
    }
  }

  getValue(eosSubjects) {
    return eosSubjects.map(res => res.value);
  }
}
