import {Component, Input, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {Subscriber, Subscription} from "rxjs";
import {OrcidService} from "./orcid.service";
import {ResultLandingInfo} from "../utils/entities/resultLandingInfo";
import {ResultLandingService} from "../landingPages/result/resultLanding.service";
import {properties} from "../../../environments/environment";
import {Session} from "../login/utils/helper.class";
import {LoginErrorCodes} from "../login/utils/guardHelper.class";
import {ExternalIDV3_0, WorkV3_0} from "./orcidWork";
import {EnvProperties} from "../utils/properties/env-properties";
import {UserManagementService} from "../services/user-management.service";
import {OpenaireEntities} from "../utils/properties/searchFields";
import {FullScreenModalComponent} from "../utils/modal/full-screen-modal/full-screen-modal.component";
import {LogService} from "../utils/log/log.service";
import {UserProfileService} from "../services/userProfile.service";

declare var UIkit: any;

@Component({
  selector: 'orcid-work',
  template: `
    <ng-container *ngIf="pageType == 'landing' || pageType == 'search'">
      <span *ngIf="!putCodes || putCodes.length == 0"
                  [ngClass]="isMobile && pageType == 'landing' ? ' uk-width-1-1' : ''"
                  [attr.uk-tooltip]="isMobile? 'cls: uk-invisible' : 'pos: bottom; cls: uk-active uk-text-small uk-padding-small'"
                  [title]="(noPids || !isLoggedIn)  ? ((noPids) ? tooltipNoPid : tooltipNoLoggedInUser) : tooltipAdd">
        <span (click)="currentAction='add'; saveWorkPreparation();"
              [class.uk-disabled]="isDisabled"
              [class.clickable]="!isDisabled">
          <a class="uk-flex uk-flex-middle uk-button-link"
             [ngClass]="isMobile && !(pageType == 'landing') ? 'uk-margin-left' : ''"
             [class.uk-text-bolder]="!(isMobile && pageType == 'landing')"
             [class.uk-text-muted]="isDisabled">
            <icon *ngIf="!showLoading" [class.text-orcid]="properties.environment != 'beta' && !showLoading && isLoggedIn && (pids || identifiers?.size > 0)"
                  [class.uk-text-muted]="isDisabled"
                  name="orcid_add" [ratio]="(isMobile && pageType == 'search') ? 0.7 : 1" visuallyHidden="add"></icon>
            <span *ngIf="showLoading" class="uk-icon"><loading
              [top_margin]="false" [size]="'small'"></loading></span>
            <span [ngClass]="(isMobile && pageType == 'landing') ? 'uk-margin-small-left' : 'uk-margin-xsmall-left'">Claim</span>
          </a>
          <div *ngIf="isMobile && pageType == 'landing'" class="uk-margin-xsmall-top uk-padding uk-padding-remove-vertical uk-text-meta uk-text-xsmall"
               [innerHTML]="(noPids || !isLoggedIn)  ? ((noPids) ? tooltipNoPid : tooltipNoLoggedInUser) : tooltipAdd"></div>
        </span>
      </span>

      <span *ngIf="putCodes && putCodes.length > 0" [ngClass]="isMobile && pageType == 'landing' ? ' uk-width-1-1' : ''"
            [attr.uk-tooltip]="isMobile? 'cls: uk-invisible' : 'pos: bottom; cls: uk-active uk-text-small uk-padding-small'"
            [title]="(noPids || !isLoggedIn)  ? ((noPids) ? tooltipNoPid : tooltipNoLoggedInUser) : tooltipDelete">
        <span (click)="currentAction='delete'; deleteWorks();"
              [class.uk-disabled]="isDisabled"
              [class.clickable]="!isDisabled">
          <a class="uk-flex uk-flex-middle uk-button-link"
             [ngClass]="isMobile && !(pageType == 'landing') ? 'uk-margin-left' : ''"
             [class.uk-text-bolder]="!(isMobile && pageType == 'landing')"
             [class.uk-text-muted]="isDisabled">
            <icon *ngIf="!showLoading" [class.text-orcid]="!showLoading && isLoggedIn && (pids || identifiers?.size > 0)"
                  [class.uk-text-muted]="isDisabled" 
                  name="orcid_bin" [ratio]="(isMobile && pageType == 'search') ? 0.7 : 1" visuallyHidden="delete"></icon>
            <span *ngIf="showLoading" class="uk-icon"><loading
                  [top_margin]="false" [size]="'small'"></loading></span>
            <span [ngClass]="(isMobile && pageType == 'landing') ? 'uk-margin-small-left' : 'uk-margin-xsmall-left'">Remove</span>
          </a>
          <div *ngIf="isMobile && pageType == 'landing'" class="uk-margin-xsmall-top uk-padding uk-padding-remove-vertical uk-text-meta uk-text-xsmall"
               [innerHTML]="(noPids || !isLoggedIn)  ? ((noPids) ? tooltipNoPid : tooltipNoLoggedInUser) : tooltipDelete"></div>
        </span>
      </span>
    </ng-container>

    <modal-alert *ngIf="!isMobile" #grantModal [overflowBody]=false (alertOutput)="openGrantWindow()">
      <div>
        <div>{{requestGrantMessage}}</div>
      </div>
    </modal-alert>
    
    <fs-modal *ngIf="isMobile" #grantFsModal classTitle="uk-tile-default uk-border-bottom">
      <div>{{requestGrantMessage}}</div>
      <button class="uk-margin-medium-top uk-button uk-button-primary uk-align-center" (click)="openGrantWindow()">
        Grant OpenAIRE
      </button>
    </fs-modal>


    <ng-container *ngIf="pageType == 'my_search'">
      <ng-container *ngIf="!showOnlyUpdateButton">
        <span class="uk-margin-bottom uk-flex uk-flex-middle uk-flex-center">
          <span>ORCID&#160;</span>
          <img src="assets/common-assets/common/ORCIDiD_icon16x16.png" alt="" loading="lazy">
          <span>&#160;ACTIONS</span>
        </span>
  
        <span [attr.uk-tooltip]="(!putCodes || putCodes.length == 0)
                        ? 'This work is currently deleted.'
                      : 'View this work from your ORCID record'">
          <a (click)="currentAction='get'; getOrcidWorks()"
             [class]="'uk-button uk-button-default action uk-flex uk-flex-middle '+ ((showLoading || !putCodes || putCodes.length == 0) ? 'uk-disabled' : '')">
            <icon *ngIf="!showLoading || currentAction!='get'" name="visibility" ratio="1" flex="true"></icon>
            
            <span *ngIf="showLoading && currentAction=='get'" class="uk-icon icon-button"><loading [top_margin]="false"
                                                                                                   [size]="'small'"></loading></span>
            <span class="uk-margin-small-left">View ORCID work</span>
          </a>
        </span>
      </ng-container>
      <ng-container *ngIf="showUpdateButton">
        <span [attr.uk-tooltip]="(!putCodes || putCodes.length == 0)
                        ? 'This work is currently deleted.'
                      : ('Update this work to your ORCID record' + ((properties.environment == 'beta') ? '. The action will affect your real ORCID iD.' : '')
                      + showUpdateDatesInTooltip())">
          <a (click)="currentAction='update'; updateWorkPreparation()"
             [class]="'uk-button uk-button-default action uk-margin-top uk-flex uk-flex-middle '+ ((showLoading || !putCodes || putCodes.length == 0) ? 'uk-disabled' : '')">
            <icon *ngIf="!showLoading || currentAction!='update'" name="refresh" ratio="1" flex="true"></icon>
            <span *ngIf="showLoading && currentAction=='update'" class="uk-icon icon-button"><loading [top_margin]="false"
                                                                                                      [size]="'small'"></loading></span>
            <span class="uk-margin-small-left">Update ORCID work</span>
          </a>
        </span>
      </ng-container>
      <ng-container *ngIf="!showOnlyUpdateButton">
        <span *ngIf="!putCodes || putCodes.length == 0"
              [attr.uk-tooltip]="tooltipAdd">
          <a (click)="currentAction='add'; saveWorkPreparation();"
             [class]="'uk-button uk-button-default action uk-margin-top uk-flex uk-flex-middle '+ (showLoading ? 'uk-disabled' : '')">
            <icon *ngIf="!showLoading || currentAction!='add'" name="add" ratio="1" flex="true"></icon>
            <span *ngIf="showLoading && currentAction=='add'" class="uk-icon icon-button"><loading [top_margin]="false"
                                                                                                   [size]="'small'"></loading></span>
            <span class="uk-margin-small-left">Claim</span>
          </a>
        </span>

        <span *ngIf="putCodes && putCodes.length > 0"
            [attr.uk-tooltip]="tooltipDelete">
        <a (click)="currentAction='delete'; deleteWorks();"
           [class]="'uk-button uk-button-default action uk-margin-top uk-flex uk-flex-middle '+ (showLoading ? 'uk-disabled' : '')">
          <icon *ngIf="!showLoading || currentAction!='delete'" name="delete" ratio="1" flex="true"></icon>
          <span *ngIf="showLoading && currentAction=='delete'" class="uk-icon icon-button"><loading [top_margin]="false"
                                                                                                    [size]="'small'"></loading></span>
          <span class="uk-margin-small-left">Remove</span>
        </a>
      </span>
      </ng-container>
    </ng-container>

    <modal-alert #workModal large="true">
      <div *ngIf="orcidWorks">
        <div *ngFor="let work of orcidWorks">
          <ng-container *ngIf="work.work">
            <ng-container *ngTemplateOutlet="orcidWorkPreview; context:{work: work['work']}"></ng-container>
          </ng-container>
        </div>
      </div>
    </modal-alert>

    <ng-template #orcidWorkPreview let-work="work">
      <div class="uk-card uk-card-default uk-padding uk-card-hover">
        <div>{{work.title?.title?.value}}</div>
        <div>{{work.title?.subtitle?.value}}</div>

        <div class="uk-text-uppercase">{{work['journal-title']?.value}}</div>

        <div *ngIf="work['publication-date'] || work['type']" class="uk-text-small uk-margin-small-bottom">
          <span *ngIf="work['publication-date']">
            <span *ngIf="work['publication-date']['year'] && work['publication-date']['year'].value">
              {{work['publication-date']?.year?.value}}
            </span>
            <span *ngIf="work['publication-date']['year'] && work['publication-date']['year'].value
                          && (
              (work['publication-date']['month'] && work['publication-date']['month'].value) || (work['publication-date']['day'] && work['publication-date']['day'].value))">
              -
            </span>
            <span *ngIf="work['publication-date']['month'] && work['publication-date']['month'].value">
              {{work['publication-date']?.month?.value}}
            </span>
            <span *ngIf="work['publication-date']['month'] && work['publication-date']['month'].value
                          && (work['publication-date']['day'] && work['publication-date']['day'].value) ">
              -
            </span>
            <span *ngIf="work['publication-date']['day'] && work['publication-date']['day'].value">
              {{work['publication-date']?.day?.value}}
            </span>
            
            <span *ngIf="work['type']"> | </span>
          </span>

          <span>{{work['type']}}</span>
        </div>

        <!-- Description -->
        <div *ngIf="work['short-description']" class="uk-margin-small-bottom multi-line-ellipsis lines-3">
          <p class="uk-text-muted uk-text-small">
            {{work['short-description']}}
          </p>
        </div>

        <div *ngIf="work['external-ids'] && work['external-ids']['external-id']" class="uk-margin-small-bottom">
          <showIdentifiers [identifiers]="parseIdentifiers(work['external-ids']['external-id'])"></showIdentifiers>
        </div>

        <div *ngIf="work['contributors'] && work['contributors']['contributor']">
          <div *ngFor="let contributor of work['contributors']['contributor']">
            <span *ngIf="contributor['credit-name'] && contributor['credit-name'].value">
              {{contributor['credit-name']?.value}}
            </span>
            <span *ngIf="(contributor['credit-name'] && contributor['credit-name'].value) && (
                  (contributor['contributor-attributes'] && contributor['contributor-attributes']['contributor-role'])
                  ||
                  (contributor['contributor-attributes'] && contributor['contributor-attributes']['contributor-sequence'])
                  ||
                  (contributor['contributor-orcid'] && contributor['contributor-orcid']['path'])
            )">
              (
            </span>
            <span
                *ngIf="contributor['contributor-attributes'] && contributor['contributor-attributes']['contributor-role']">
              {{contributor['contributor-attributes']['contributor-role']}}
            </span>
            <span *ngIf="(contributor['contributor-attributes'] && contributor['contributor-attributes']['contributor-role'])
                        && (contributor['contributor-attributes']['contributor-sequence'] || (contributor['contributor-orcid'] && contributor['contributor-orcid']['path']))">
              ,
            </span>
            <span
                *ngIf="contributor['contributor-attributes'] && contributor['contributor-attributes']['contributor-sequence']">
              {{contributor['contributor-attributes']['contributor-sequence']}}
            </span>
            <span *ngIf="contributor['contributor-attributes'] && contributor['contributor-attributes']['contributor-sequence']
                        && contributor['contributor-orcid'] && contributor['contributor-orcid']['path']">
              ,
            </span>
            <span *ngIf="contributor['contributor-orcid'] && contributor['contributor-orcid']['path']">
              {{contributor['contributor-orcid']?.path}}
            </span>
            <span *ngIf="(contributor['credit-name'] && contributor['credit-name'].value) && (
                  (contributor['contributor-attributes'] && contributor['contributor-attributes']['contributor-role'])
            ||
            (contributor['contributor-attributes'] && contributor['contributor-attributes']['contributor-sequence'])
            ||
            (contributor['contributor-orcid'] && contributor['contributor-orcid']['path'])
            )">
            )
            </span>
          </div>
        </div>
      </div>
    </ng-template>

    <modal-alert #propagationModal (alertOutput)="confirmedPropagation()">
      <div>
        This {{openaireEntities.RESULT}} is the result of <span
          class="uk-text-bold"> merged  {{openaireEntities.RESULTS}} in OpenAIRE</span>.
        <br><br>
        You have already added <span class="uk-text-bold">{{this.putCodes?.length}} works</span> in your ORCID record
        related to the merged {{openaireEntities.RESULT}}.
        <div *ngIf="currentAction == 'delete'">
          If you continue with delete action, <span class="uk-text-bold">all these works will be deleted</span>.
        </div>
        <div *ngIf="currentAction == 'update'">
          If you continue with update action, <span class="uk-text-bold">all these works will be deleted and a new merged work will be added</span>
          instead.
        </div>
      </div>
    </modal-alert>
    
    <fs-modal #propagationFsModal classTitle="uk-tile-default uk-border-bottom">
      <div>
        This {{openaireEntities.RESULT}} is the result of <span
        class="uk-text-bold"> merged  {{openaireEntities.RESULTS}} in OpenAIRE</span>.
        <br><br>
        You have already added <span class="uk-text-bold">{{this.putCodes?.length}} works</span> in your ORCID record
        related to the merged {{openaireEntities.RESULT}}.
        <div *ngIf="currentAction == 'delete'">
          If you continue with delete action, <span class="uk-text-bold">all these works will be deleted</span>.
        </div>
        <div *ngIf="currentAction == 'update'">
          If you continue with update action, <span class="uk-text-bold">all these works will be deleted and a new merged work will be added</span>
          instead.
        </div>
      </div>

      <button class="uk-margin-medium-top uk-button uk-button-primary uk-align-center" (click)="confirmedPropagation()">
        Continue
      </button>
    </fs-modal>
  `
})

export class OrcidWorkComponent {
  @Input() isMobile: boolean = false;
  @Input() resultId: string = "";
  @Input() resultTitle: string = "";
  @Input() resultLandingInfo: ResultLandingInfo;
  @Input() pids: string = "";
  @Input() identifiers: Map<string, string[]>;
  @Input() type: string;
  @Input() putCodes: string[] = [];
  @Input() creationDates: string[] = [];
  @Input() updateDates: string[] = [];
  @Input() givenPutCode: boolean = false;
  @Input() pageType: string = "search";

  //for myorcid links page
  @Input() showOnlyUpdateButton: boolean = false;
  @Input() showUpdateButton: boolean = true;
  public subscriptions: Subscription[] = [];
  @ViewChild('workModal') workModal;
  // @ViewChild('saveWorkModal') saveWorkModal;
  @ViewChild('grantModal') grantModal;
  @ViewChild('grantFsModal') grantFsModal: FullScreenModalComponent;
  // @ViewChild('messageModal') messageModal;
  @ViewChild('propagationModal') propagationModal;
  @ViewChild('propagationFsModal') propagationFsModal;

  public requestGrant: boolean = false;
  public requestGrantMessage: string = "Please grant OpenAIRE to access and update your ORCID works.";
  private tokenUrl: string;
  public message: string = "";
  public showLoading: boolean = false;
  
  public works: any[] = [];
  public orcidWorks: any[] = [];
  public window: any;
  
  public isLoggedIn: boolean = false;
  public hasConsent: boolean = false;
  public currentAction: string = "";
  
  public properties: EnvProperties = properties;
  public openaireEntities = OpenaireEntities;
  
  constructor(private route: ActivatedRoute,
              private _router: Router,
              private orcidService: OrcidService,
              private resultLandingService: ResultLandingService,
              private userManagementService: UserManagementService, private _logService: LogService, private _userProfileService: UserProfileService) {
    if (typeof document !== 'undefined') {
      this.tokenUrl = properties.orcidTokenURL
        + "client_id=" + properties.orcidClientId
        // + "&response_type=code&scope=/activities/update"
        // + "&response_type=code&scope=/authenticate /activities/update /person/update /read-limited"
        + "&response_type=code&scope=/activities/update /read-limited"
        + "&redirect_uri=" + location.origin + "/orcid?source=openaire";
    }
  }
  
  ngOnInit() {
    if(this.properties.environment != 'beta') {
      this.subscriptions.push(this.userManagementService.getUserInfo().subscribe(user => {
        if (user) {
          this.isLoggedIn = true;
          if (!this.givenPutCode) {
            this.getPutCode();
          }
        } else {
          this.isLoggedIn = false;
        }
      }, error => {
        this.isLoggedIn = false;
      }));
      if (properties.dashboard == 'irish') {
        this.subscriptions.push(this._userProfileService.getUserProfile().subscribe(userProfile => {
          this.hasConsent = userProfile.consent;
        }, error => {
          this.hasConsent = false;
        }));
      }
    }
  }
  
  ngOnDestroy() {
    this.subscriptions.forEach(subscription => {
      if (subscription instanceof Subscriber) {
        // console.debug("subscription closing...");
        subscription.unsubscribe();
      }
    });
  }
  
  public showUpdateDatesInTooltip() {
    const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    let response: string = "";
    if (this.updateDates != null && this.updateDates.length > 0) {
      response += "<br><br> Last update in ORCID<br>";
      for (let i = 0; i < this.updateDates.length; i++) {
        let date: Date = new Date(this.updateDates[i]);
        response += "<span>" + date.getDate() + " " + monthNames[date.getMonth()] + " " + date.getFullYear();
        if (i < this.updateDates.length - 1) {
          response += "& ";
        }
        response += "</span>";
      }
    }
    return response;
  }
  
  public parseIdentifiers(identifiers: ExternalIDV3_0[]): Map<string, string[]> {
    let identifiersMap: Map<string, string[]> = new Map<string, string[]>();
    for (let identifier of identifiers) {
      if (!identifiersMap.has(identifier['external-id-type'])) {
        identifiersMap.set(identifier['external-id-type'], new Array<string>());
      }
      identifiersMap.get(identifier['external-id-type']).push(identifier['external-id-value']);
    }
    return identifiersMap;
  }
  
  openGrantWindow() {
    if (!this.isLoggedIn) {
      //this.userValidMessage = "User session has expired. Please login again.";
      this._router.navigate(['/user-info'], {
        queryParams: {
          "errorCode": LoginErrorCodes.NOT_VALID,
          "redirectUrl": this._router.url
        }
      });
    } else {
      // this.tokenUrl = location.origin+"/orcid";
      this.window = window.open(this.tokenUrl, '_blank',
        'location=yes,height=700,width=540,left=500,top=100,scrollbars=yes,status=yes');
      // this.requestGrant = false;
      this.closeGrantModal();
      
      let self = this;
      window.onmessage = function (ev) {
        if (ev.isTrusted && ev.origin == location.origin && ev.data == 'success') {
          self.requestGrant = false;
          UIkit.notification({
            message: 'Thank you for <strong>connecting your ORCID iD</strong> with OpenAIRE!',
            status: 'success',
            timeout: 6000,
            pos: 'bottom-right'
          });
          if (self.currentAction == "add") {
            self.saveWorkPreparation();
          } else if (self.currentAction == "delete") {
            self.deleteWorks();
          } else if (self.currentAction == "update") {
            self.updateWorkPreparation();
          }
        }
      }
    }
  }
  
  private getPutCode() {
    this.subscriptions.push(this.orcidService.getPutCode(this.pids).subscribe(
      putCodes => {
        this.putCodes = putCodes;
      }, error => {
      
      }
    ))
  }
  
  private getResultLandingInfo(action: string) {
    this.subscriptions.push(this.resultLandingService.getResultLandingInfo(this.resultId, null, this.type, null, properties).subscribe(
      resultLandingInfo => {
        this.resultLandingInfo = resultLandingInfo;
        if (this.resultLandingInfo && this.resultLandingInfo.identifiers) {
          let pidsArray: string[] = [];
          for (let key of Array.from(this.resultLandingInfo.identifiers.keys())) {
            pidsArray = pidsArray.concat(this.resultLandingInfo.identifiers.get(key));
          }
          this.pids = pidsArray.join();
        }
        if (action == "save") {
          this.saveWork();
        } else if (action == "update") {
          this.updateWork();
        }
      },
      error => {
        this.handleError(error);
        console.error("Error getting landing info: ", error);
      }
    ))
  }
  
  public saveWorkPreparation() {
    if (!this.isLoggedIn) {
      //this.userValidMessage = "User session has expired. Please login again.";
      this._router.navigate(['/user-info'], {
        queryParams: {
          "errorCode": LoginErrorCodes.NOT_VALID,
          "redirectUrl": this._router.url
        }
      });
    } else {
      if(properties.dashboard == 'irish' && !this.hasConsent){
        this._router.navigate(['/consent'], {
          queryParams: {
            "errorCode": LoginErrorCodes.NOT_VALID,
            "redirectUrl": this._router.url
          }
        });
        return;
      }
      if (this.requestGrant) {
        this.openGrantModal("Add, delete or edit work in your ORCID record");
      } else {
        this.showLoading = true;
        
        if (this.resultLandingInfo) {
          this.saveWork();
        } else {
          this.getResultLandingInfo("save");
        }
      }
    }
  }
  
  private saveWork() {
    this.subscriptions.push(this.orcidService.saveWork(this.resultLandingInfo, this.pids).subscribe(
      response => {
        if(this.properties.logServiceUrl) {
          this.subscriptions.push(this._logService.logOrcidLink(this.properties, "added", this.resultLandingInfo.title, this.resultLandingInfo.identifiers.get('doi')[0]).subscribe(res => { }));
        }
        // for testing only
        // this.openGrantModal("Add work in your ORCID record");
        // this.requestGrant = true;
        // this.requestGrantMessage = "Please grant OpenAIRE to access and update your ORCID record and works.";
        
        if (response == null) {
          this.handleError(null);
          console.error("Error posting landing info: null");
        } else {
          this.putCodes.push("" + response['put-code']);
          this.creationDates.push(response['created-date']['value']);
          this.updateDates.push(response['last-modified-date']['value']);
          
          // this.closeGrantModal();
          // this.message = "You have successfully added work with pids: "+this.pids+" in your ORCID record!";
          this.message = "You have successfully added work \"" + this.resultTitle + "\" in your ORCID record!";
          // this.openMessageModal("Work added successfully");
          
          // message: 'You have <strong>successfully added</strong> work with pids: <strong>'+this.pids+'</strong> in your ORCID record!',
          UIkit.notification({
            message: 'You have <strong>successfully added</strong> work "<strong>' + this.resultTitle + '</strong>" in your ORCID record!'
            // +
            // '<br><br><a class="uk-link" [href]="goToOrcidLinksPage()">Manager your ORCID links</a>'
            ,
            // '<br><br><a class="uk-link" (click)="goToOrcidLinksPage()">Manager your ORCID links</a>',
            // '<br><br><a class="uk-link" routerLinkActive="router-link-active" [routerLink]="myOrcidLinksPage">Manager your ORCID links</a>',
            status: 'success',
            timeout: 6000,
            pos: 'bottom-right'
          });
          
          this.showLoading = false;
        }
      },
      error => {
        this.handleError(error);
        console.error("Error posting landing info", error);
      }
    ));
  }
  
  goToOrcidLinksPage() {
    this._router.navigate([this.properties.myOrcidLinksPage]);
  }
  
  private updateWorkPreparation() {
    if (!Session.isLoggedIn()) {
      this._router.navigate(['/user-info'], {
        queryParams: {
          "errorCode": LoginErrorCodes.NOT_VALID,
          "redirectUrl": this._router.url
        }
      });
    } else {
      
      if (this.requestGrant) {
        this.openGrantModal("Add, delete or edit work in your ORCID record");
      } else if (this.putCodes.length > 1) {
        this.openPropagationModal("Update ORCID work");
      } else {
        this.showLoading = true;
        
        if (this.resultLandingInfo) {
          this.updateWork();
        } else {
          this.getResultLandingInfo("update");
        }
      }
    }
  }
  
  private updateWork() {
    this.subscriptions.push(this.orcidService.updateWork(this.resultLandingInfo, this.pids, this.putCodes[0]).subscribe(
      response => {
        if (response) {
          this.updateDates[0] = response['last-modified-date'].value;
          
          // message: 'You have <strong>successfully updated</strong> work with pids: <strong>' + this.pids + '</strong> in your ORCID record!',
          UIkit.notification({
            message: 'You have <strong>successfully updated</strong> work "<strong>' + this.resultTitle + '</strong>" in your ORCID record!'
            // +
            // '<br><br><a routerLinkActive="router-link-active" [routerLink]="myOrcidLinksPage">Manager your ORCID links</a>'
            ,
            status: 'success',
            timeout: 6000,
            pos: 'bottom-right'
          });
        }
        this.showLoading = false;
      },
      error => {
        this.handleError(error);
        console.error("Error updating landing info", error);
      }
    ));
  }
  
  public confirmedPropagation() {
    this.propagationModal.cancel();
    
    this.deleteWorks(true);
    //}
    // if(this.currentAction == "update") {
    //   this.saveWork();
    // }
  }
  
  public getOrcidWorks() {
    if (!Session.isLoggedIn()) {
      this._router.navigate(['/user-info'], {
        queryParams: {
          "errorCode": LoginErrorCodes.NOT_VALID,
          "redirectUrl": this._router.url
        }
      });
    } else {
      this.showLoading = true;
      this.subscriptions.push(this.orcidService.getOrcidWorks(this.putCodes).subscribe(
        (response) => {
          let error: boolean = true;
          if (response && response['bulk']) {
            response = response['bulk'].filter(res => {
              return (!res.error && res.work);
            });
            if (response && response.length > 0) {
              error = false;
              this.orcidWorks = response;
              this.openWorkModal();
            }
          }
          if (error) {
            UIkit.notification({
              message: 'There was an error getting this work. </br> Please make sure you have not deleted it from your ORCID iD.',
              status: 'warning',
              timeout: 6000,
              pos: 'bottom-right'
            });
          }
          this.showLoading = false;
        },
        error => {
          this.handleError(error);
          console.error("Error getting work", error);
        }
      ));
    }
  }
  
  
  public deleteWorks(confirmed: boolean = false) {
    if (!Session.isLoggedIn()) {
      this._router.navigate(['/user-info'], {
        queryParams: {
          "errorCode": LoginErrorCodes.NOT_VALID,
          "redirectUrl": this._router.url
        }
      });
    } else {
      
      if (this.requestGrant) {
        this.openGrantModal("Add, delete or edit work in your ORCID record");
      } else if (this.putCodes.length > 1 && !confirmed) {
        this.openPropagationModal("Delete ORCID work");
      } else {
        this.showLoading = true;
        
        if (!this.resultLandingInfo && this.identifiers) {
          let pidsArray: string[] = [];
          for (let key of Array.from(this.identifiers.keys())) {
            pidsArray = pidsArray.concat(this.identifiers.get(key));
          }
          this.pids = pidsArray.join();
        }
        
        this.subscriptions.push(this.orcidService.deleteWorks(this.putCodes).subscribe(
          deletedPutCodes => {
            let deletedAll: boolean = true;
            
            if (deletedPutCodes) {
              for (let i = 0; i < deletedPutCodes.length; i++) {
                let deletedPutCode = deletedPutCodes[i];
                if(this.properties.logServiceUrl) {
                  this.subscriptions.push(this._logService.logRemoveOrcidLink(this.properties, deletedPutCode).subscribe(res => { }));
                }
                if (deletedPutCode == null) {
                  deletedAll = false;
                } else {
                  this.putCodes.splice(i, 1);
                  this.creationDates.splice(i, 1);
                  this.updateDates.splice(i, 1);
                  // this.works.splice(i, 1);
                }
              }
            } else {
              deletedAll = false;
            }
            
            if (!deletedAll) {
              this.handleError(null);
              console.error("Error deleting landing info: null");
            } else {
              if (this.currentAction == "update") {
                this.saveWork();
              } else {
                // this.closeGrantModal();
                // this.message = "You have successfully deleted work with pids: " + this.pids + " from your ORCID record!";
                this.message = "You have successfully deleted work \"" + this.resultTitle + "\" from your ORCID record!";
                // this.openMessageModal("Work deleted successfully");
                
                // message: 'You have <strong>successfully deleted</strong> work with pids: <strong>' + this.pids + '</strong> from your ORCID record!',
                UIkit.notification({
                  message: 'You have <strong>successfully deleted</strong> work "<strong>' + this.resultTitle + '</strong>" from your ORCID record!'
                  // +
                  // '<br><br><a routerLinkActive="router-link-active" [routerLink]="myOrcidLinksPage">Manager your ORCID links</a>'
                  ,
                  status: 'success',
                  timeout: 6000,
                  pos: 'bottom-right'
                });
                this.showLoading = false;
              }
            }
          },
          error => {
            this.handleError(error);
            console.error("Error deleting work", error);
          }
        ));
      }
    }
  }
  
  openGrantModal(title: string) {
    if(this.isMobile) {
      this.grantFsModal.okButton = false;
      this.grantFsModal.title = title;
      this.grantFsModal.open();
    } else {
      this.grantModal.cancelButton = true;
      this.grantModal.okButton = true;
      this.grantModal.okButtonText = "Grant OpenAIRE";
      this.grantModal.okButtonLeft = false;
      this.grantModal.alertTitle = title;
      this.grantModal.open();
    }
  }
  
  closeGrantModal() {
    this.grantModal.cancel();
  }
  
  openWorkModal() {
    this.workModal.cancelButton = false;
    this.workModal.okButton = false;
    this.workModal.alertTitle = "Work in your ORCID record";
    this.workModal.open();
  }
  
  closeWorkModal() {
    this.workModal.cancel();
  }
  
  // openMessageModal(title: string) {
  //   this.messageModal.cancelButton = false;
  //   this.messageModal.okButton = false;
  //   this.messageModal.alertTitle = title;
  //   this.messageModal.open();
  // }
  //
  // closeMessageModal() {
  //   this.messageModal.cancel();
  // }
  
  openPropagationModal(title: string) {
    if(this.isMobile) {
      this.propagationFsModal.okButton = false;
      this.propagationFsModal.title = title;
      this.propagationFsModal.open();
    } else {
      this.propagationModal.cancelButton = true;
      this.propagationModal.okButton = true;
      this.propagationModal.okButtonText = "Continue";
      this.propagationModal.okButtonLeft = false;
      this.propagationModal.alertTitle = title;
      this.propagationModal.open();
    }
  }
  
  closePropagationModal() {
    this.propagationModal.cancel();
  }
  
  handleError(error) {
    if (error && error.status == "401") {
      this.openGrantModal("Add, delete or edit work in your ORCID record");
      this.requestGrant = true;
      this.requestGrantMessage = "Please grant OpenAIRE to access and update your ORCID record and works. ";
      // + "If you have already granted OpenAIRE, you just need to login again to ORCID!";
    } else if (error && error.status == "403") {
      this.openGrantModal("Add, delete or edit work in your ORCID record");
      this.requestGrant = true;
      this.requestGrantMessage = "Please login again to ORCID."
      // this.openGrantModal();
    } else {
      this.message = "";
      if (error && error.status == "409") {
        this.message = "There is <span class='uk-text-bold'>already a work in your ORCID record</span> with the same information of the work you are trying to add now. <br><br>";
      }
      if (this.currentAction == "get") {
        // this.message += "There was an <span class='uk-text-bold'>error getting</span> work with pids: <span class='uk-text-bold'>" + this.pids + "</span> from your ORCID record. <br> Please try again later.";
        this.message += "There was an <span class='uk-text-bold'>error getting</span> work \"<span class='uk-text-bold'>" + this.resultTitle + "</span>\" from your ORCID record. <br> Please try again later.";
      } else if (this.currentAction == "add") {
        // this.message += "There was an <span class='uk-text-bold'>error adding</span> work with pids: <span class='uk-text-bold'>"+this.pids+"</span> to your ORCID record. <br> Please try again later.";
        this.message += "There was an <span class='uk-text-bold'>error adding</span> work with pids: \"<span class='uk-text-bold'>" + this.pids + "</span>\" to your ORCID record. <br> Please try again later.";
      } else if (this.currentAction == "update") {
        // this.message += "There was an <span class='uk-text-bold'>error updating</span> work with pids: <span class='uk-text-bold'>"+this.pids+"</span> to your ORCID record. <br> Please try again later.";
        this.message += "There was an <span class='uk-text-bold'>error updating</span> work \"<span class='uk-text-bold'>" + this.resultTitle + "</span>\" to your ORCID record. <br> Please try again later.";
      } else if (this.currentAction == "delete") {
        // this.message += "There was an <span class='uk-text-bold'>error deleting</span> work with pids: <span class='uk-text-bold'>"+this.pids+"</span> from your ORCID record. <br> Please try again later.";
        this.message += "There was an <span class='uk-text-bold'>error deleting</span> work \"<span class='uk-text-bold'>" + this.resultTitle + "</span>\" from your ORCID record. <br> Please try again later.";
      } else {
        this.message += "There was an error. Please try again later."
      }
      
      UIkit.notification({
        message: this.message,
        status: 'danger',
        timeout: 6000,
        pos: 'bottom-right'
      });
      // this.openMessageModal("An error occured");
    }
    this.showLoading = false;
  }

  get tooltipBETA() {
    // return "Login to the production environment to add works to your <span class=\"text-orcid\">ORCID</span> record";
    return "Add or delete a work from your <span class=\"text-orcid\">ORCID</span> record. This feature is not available on BETA.";
  }

  get tooltipAdd() {
    return (properties.environment == "beta") ? this.tooltipBETA : ("Add this work to your <span class=\"text-orcid\">ORCID</span> record" + ((properties.environment == "test") ? ". The action will affect your real ORCID iD." : ""));
  }
  
  get tooltipDelete() {
    return "Delete this work from your <span class=\"text-orcid\">ORCID</span> record" + ((properties.environment == "test") ? ". The action will affect your real ORCID iD." : "");
  }
  
  get tooltipNoPid() {
    return "Only resources with a PID (persistent identifier) like DOI, handle, PMID can be added or deleted from your <span class=\"text-orcid\">ORCID</span> record";
  }
  
  get tooltipNoLoggedInUser() {
    return (properties.environment == "beta") ? this.tooltipBETA : "Add or delete a work from your <span class=\"text-orcid\">ORCID</span> record. Please log in first."
  }

  get isDisabled() {
    return (this.properties.environment == 'beta' || this.showLoading || !this.isLoggedIn || (!this.pids && (!this.identifiers || this.identifiers.size == 0)));
  }

  get noPids() {
    return (!this.pids && (!this.identifiers || this.identifiers.size == 0));
  }
}
