import {Component, Inject, Input, OnDestroy, OnInit, RendererFactory2, ViewEncapsulation} from '@angular/core';
import {Citation, CitationData} from './citation.class';
import {DOCUMENT} from "@angular/common";
import {EnvProperties} from "../../../utils/properties/env-properties";
import {properties} from "../../../../../environments/environment";
import {PiwikService} from "../../../utils/piwik/piwik.service";

declare var Cite: any;
// Based on https://citation.js.org/api/tutorial-getting_started.html browser release
//<citeThis ></citeThis>
@Component({
  selector: 'citeThis',
  template: `
    <div class="uk-padding uk-padding-remove-top uk-height-min-large">
      <div input type="select" placeholder="Select a citation style" inputClass="flat x-small"
           [options]="citation.templates" [(value)]="selectedStyle"
           (valueChange)="styleChanged()"></div>
      <div *ngIf="selectedStyle" class="clipboard-wrapper box-content uk-grid uk-margin-auto uk-margin-small-top ">
        <div id="citation" class="uk-overflow-auto uk-padding-small uk-padding-remove-vertical uk-margin-top" [innerHTML]=citationText></div>
        <div class="uk-width-1-1 uk-padding-small uk-text-right">
          <a class="uk-link copy clipboard_btn" data-clipboard-target="#citation" title="Copy citation">
            COPY CITATION
          </a>
        </div>
      </div>
      
      <div  class="uk-margin-large-top">
        <div input type="select" placeholder="Select file format to download" inputClass="flat x-small"
             [options]="citation.fileFormatOptions" [(value)]="selectedFormat"
             (valueChange)="formatChanged()"></div>
        <button  *ngIf="selectedFormat" class="  uk-button uk-button-primary uk-button-small uk-margin-small-top uk-icon uk-float-right"
                title="Copy to clipboard" [disabled]="!selectedFormat" (click)="downloadFile()">
          <span class="custom-icon " uk-icon="download"></span>
          <span class="uk-margin-small-left">Download</span>
        </button>
      </div>
    </div>
  `
})
export class CiteThisComponent implements OnInit, OnDestroy {
  public selectedStyle: string = null;
  public selectedFormat: string = null;
  public fileText: string;
  properties:EnvProperties;
  public citationText: string;
  public citation: Citation = new Citation();
  @Input() result: any;
  @Input() id: string;
  @Input() type: string = "article";
  public data:CitationData;
  public clipboard;
  timeout;
  cite;citeConfig;
  sub;
  constructor( @Inject(DOCUMENT) private document, private rendererFactory: RendererFactory2, private _piwikService: PiwikService){
}
  ngOnInit() {
    this.properties = properties;
    try{
      if (!this.document.getElementById('citationjs')) {
        const renderer = this.rendererFactory.createRenderer(this.document, {
          id: '-1',
          encapsulation: ViewEncapsulation.None,
          styles: [],
          data: {}
        });
        const head = this.document.head;
        if (head === null) {
          throw new Error('<head> not found within DOCUMENT.');
        }
        const script = renderer.createElement('script');
        renderer.setAttribute(script, "id", "citationjs");
        renderer.setAttribute(script, "src", "assets/common-assets/citation-0.4.0-9.min.js");
        renderer.setAttribute(script, "type", "text/javascript");
        renderer.appendChild(head, script);
        this.timeout = setTimeout(() => {
          const script2 = renderer.createElement('script');
          renderer.setAttribute(script2, "id", "citationjs2");
          renderer.setAttribute(script2, "type", "text/javascript");
          renderer.setProperty(script2,  "text","const Cite = require('citation-js')");
          renderer.appendChild(head, script2);
        }, 1000);
      }

  }catch (e) {
    console.error(e)
  }
  }
  
  ngOnDestroy() {
    delete this.clipboard;
    clearTimeout(this.timeout);
  }
  private initiate(){
    this.citeConfig = Cite.plugins.config.get('csl');
    this.cite = new Cite();
    this.parseData();
    this.createClipboard();
  }
  private createClipboard() {
    if (typeof window !== 'undefined') {
      delete this.clipboard;
      let Clipboard;
      Clipboard = require('clipboard');
      this.clipboard = new Clipboard('.clipboard_btn');
    }
  }
  
  parseData() {
    var citationData: CitationData = new CitationData();
    
    if (this.result.identifiers && Array.from(this.result.identifiers.keys()).length > 0) {
      var keys = Array.from(this.result.identifiers.keys());
      for (var i = 0; i < keys.length; i++) {
        if (keys[i] == "doi") {
          var ids = this.result.identifiers.get(keys[i]);
          for (var j = 0; j < ids.length; j++) {
            citationData.DOI = ids[j];
            break;
          }
        }
      }
    }
    citationData.id = this.id;
    citationData.type =  this.mapTypes();
    if (this.result.title) {
      citationData.title = this.result.title;
    }
    if (this.result.publisher) {
      citationData.publisher = this.result.publisher;
    }
    if (this.result.authors) {
      citationData.author = [];
      var max_length = (this.result.authors.length > 10) ? 10 : this.result.authors.length;
      for (var i = 0; i < max_length; i++) {
        if (this.result.authors[i] && this.result.authors[i].fullName && this.result.authors[i].fullName.indexOf(", ") !== -1) {
          citationData.author.push({
            given: this.result.authors[i].fullName.split(", ")[1],
            family: this.result.authors[i].fullName.split(", ")[0],
            'parse-names': true
          });
        } else {
          citationData.author.push({given: "", family: this.result.authors[i].fullName, 'parse-names': true});
        }
        // citationData.authors.push(this.result.authors[i]);
      }
    }
    if (this.result.dateofacceptance != undefined) {
      citationData.issued = {};
      var date: string = (this.result.dateofacceptance.getFullYear()) + ""; // transform to string in case it is an integer
      var dateArray: string[] = (date && (date).indexOf('-') !== -1) ? [date.split('-')[0]] : [date];
      if (dateArray.length < 3) {
        // dateArray.push[1];
        // dateArray.push[1];
      }
      citationData.issued = {"date-parts": [["" + dateArray[0]]]};
      if (this.result.date) {
        citationData.date = this.result.date;
      }
      if (this.result.journal) {
        if (this.result.journal.journal) {
          citationData["container-title"] = this.result.journal.journal;
        }
        if (this.result.journal.issn) {
          citationData.ISSN = this.result.journal.issn;
        }
        if (this.result.journal.issue) {
          citationData.issue = this.result.journal.issue;
        }
        citationData.type = "article-journal"; // in case of APA volume and pages appear only in specific types not just article
        if (this.result.journal.volume) {
          citationData.volume = this.result.journal.volume;
        }
        if (this.result.journal["start_page"] && this.result.journal["end_page"]) {
          citationData.page = this.result.journal["start_page"] + "-" + this.result.journal["end_page"];
        }
      }
    }
    
    
    this.data = citationData;
    this.cite.set(this.data);
    
  }
  private mapTypes(){
    if (this.result.types != undefined && this.result.types.length > 0) {
      if(this.result.types.indexOf("Article") != -1) {
        return "article";
      }else if(this.result.types.indexOf("Conference object") != -1){
        return "paper-conference";
      }else if( this.result.types[0]){
        return this.result.types[0].toLowerCase();
      }
    }
    return "";
  }
  styleChanged() {
    this.citationText  = this.get(this.selectedStyle);
    
  }
  formatChanged() {
    this.fileText = this.get(this.selectedFormat, false);
  }
  downloadFile(){
    if (typeof document !== 'undefined') {
      var url = window.URL.createObjectURL(new Blob([this.fileText]));
      var a = window.document.createElement('a');
      window.document.body.appendChild(a);
      a.setAttribute('style', 'display: none');
      a.href = url;
      a.download = this.selectedFormat + this.citation.fileSuffix[this.citation.fileFormats.indexOf(this.selectedFormat)];
      a.click();
      window.URL.revokeObjectURL(url);
      a.remove(); // remove the element
      this.sub = this._piwikService.trackDownload(this.properties, "DownloadCitation"+this.selectedFormat).subscribe();
    }
  }

  get(style:string, isBibliography:boolean = true){
    try {
      if (!isBibliography  && style != "bibtex") {
        return this.getFormat(style);
      } else {
        return this.getBibliography(style);
      }
    }catch (e) {
      console.error(e);
      return "";
    }
  }

  /**
   * Supports formats bibtex, bibtxt, ris
   * @param format
   */
  getFormat(format:string) {
    if(!this.cite){
      this.initiate();
    }
    return this.cite.format(format, {
      format: 'text'
    });
  }

  /**
   * Based on this and citeproc library https://citation.js.org/api/tutorial-plugins.html
   * if the template doesn't exist add the CSL xml and the library will produce the citation
   * @param template
   */

  getBibliography(template:string) {
    if(!this.cite || !this.citeConfig ){
      this.initiate();
    }
    if (!this.citeConfig.templates.get(template)) {
      this.citeConfig.templates.add(template, this.citation[template]);
    }
    return this.cite.format('bibliography', {
      format: 'text',
      template: template,
      lang: 'en-US'
    });
  }
}
