import {Component, Input, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {Location} from '@angular/common';
import {ErrorCodes} from "../../utils/properties/errorCodes";
import {ErrorMessagesComponent} from "../../utils/errorMessages.component";
import {SearchUtilsClass} from "../../searchPages/searchUtils/searchUtils.class";
import {RouterHelper} from "../../utils/routerHelper.class";
import {EnvProperties} from "../../utils/properties/env-properties";
import {properties} from "../../../../environments/environment";
import {OrcidService} from "../orcid.service";
import {Identifier} from "../../utils/string-utils.class";

@Component({
  selector: 'search-recommended-results-for-orcid',
  template: `

<!--    <div class="uk-section uk-padding-remove-bottom uk-padding-remove-top">-->
<!--      <div class="explorePanelBackground communityPanelBackground uk-padding-small">-->
<!--        <div class="uk-container uk-container-large uk-margin-small-top uk-margin-small-bottom">-->
<!--          <breadcrumbs  [light]="!!(this.communityId)" [breadcrumbs]="breadcrumbs"></breadcrumbs>-->
<!--        </div>-->
<!--      </div>-->
<!--    </div>-->
    <div class="">
      <div class="uk-container uk-container-large uk-margin-top">
        <div *ngIf="showLoading" class="uk-animation-fade uk-margin-top  uk-width-1-1" role="alert">
          <span class="loading-gif  uk-align-center"></span>
        </div>
        <div *ngIf="!showLoading && !orcidQuery" class="uk-animation-fade uk-alert uk-alert-warning" role="alert">
          An Error Occurred
        </div>
      </div>
      
      <div *ngIf="orcidQuery" class="uk-container uk-container-large uk-margin-top">

        <form 
              class="uk-margin-top uk-grid uk-margin-small-left ng-untouched ng-pristine ng-valid uk-form-width-large uk-float-right">
 
          <div class=" uk-padding-remove-left uk-margin-small-top uk-inline uk-width-expand">
            <a *ngIf="keyword.length > 0" class="uk-form-icon uk-form-icon-flip"
               (click)="keyword = ''"
               uk-icon="icon: close"></a>
            <input type="text" class="uk-input text-input-box uk-width-expand"
                   placeholder="Search by name, description, subject..." aria-describedby="sizing-addon2"
                   [(ngModel)]="keyword" name="keyword">
          </div>
          <div class="uk-padding-remove-left">    
          <button (click)="keywordChanged()" type="submit"
                  class="portal-button uk-margin-small-left uk-margin-small-top uk-button">Search
          </button>
          </div>
 
        </form>
      </div>
      
<!--      <search-research-results [simpleView]="true" type="deposit" simpleSearchLink="/participate/deposit/search" [includeOnlyResultsAndFilter]="true" >-->
<!--      </search-research-results>-->
      <search-research-results *ngIf="orcidQuery" 
                               resultType="result" usedBy="orcid" [identifiers]="identifiers" 
                               [includeOnlyResultsAndFilter]="true" [orcidQuery]="orcidQuery">
      </search-research-results>
    </div>
    `
})
export class SearchRecommendedResultsForOrcidComponent {
  private errorCodes: ErrorCodes;
  private errorMessages: ErrorMessagesComponent;
  public results =[];
  public totalResults:number  = 0 ;
  public baseUrl:string;
  public searchUtils:SearchUtilsClass = new SearchUtilsClass();
  public subscriptions: any[] = [];
  public _location:Location;

  public disableForms: boolean = false;
  public loadPaging: boolean = true;
  public oldTotalResults: number = 0;
  pagingLimit = 0;

  properties:EnvProperties;

  @Input() public communityId: string = null;

  depositLearnHowPage: string = null;
  public routerHelper:RouterHelper = new RouterHelper();
  // breadcrumbs:Breadcrumb[] = [];
  parameters = {};
  keyword  = "";

  identifiers: string[] = [];

  orcidQuery: string = "";
  public showLoading: boolean = true;

  constructor (private route: ActivatedRoute, private router: Router, private _orcidService: OrcidService) {
    this.errorCodes = new ErrorCodes();
    this.errorMessages = new ErrorMessagesComponent();
    this.searchUtils.status = this.errorCodes.LOADING;
    this.searchUtils.page =1;
  }

  public ngOnInit() {
    this.properties = properties;
    this.depositLearnHowPage = this.properties.depositLearnHowPage;
    this.baseUrl = this.properties.depositSearchPage;
    this.pagingLimit = this.properties.pagingLimit;
    // this.breadcrumbs.push({name: 'home', route: '/'}, {
    //   name: "Deposit",
    //   route: this.depositLearnHowPage
    // }, {name: "Browse repositories", route: null});

    // this.subscriptions.push(this._orcidService.getLocalWorks().subscribe(
    //   works => {
    //     console.debug(works);
    //     for(let work of works) {
    //       for(let pid of work['pids']) {
    //         let identifier: Identifier = Identifier.getIdentifierFromString(pid);
    //         this.pidsQuery += (this.pidsQuery ? " or " : "") + '(pidclassid exact "'+identifier.class+'" and pid="'+identifier.id+'")'
    //       }
    //     }
    //   },
    //   error => {
    //     this.handleError("Could not get user's ORCID works", error);
    //   }
    // ));

    this.subscriptions.push(this._orcidService.getUserOrcid().subscribe(
      orcidId => {
        orcidId = "0000-0001-7291-3210";//"0000-0002-0458-1004";
        // console.debug("mocked orcidIdrcidId: "+orcidId);
        this.orcidQuery = 'authorid exact "'+orcidId+'" and (authoridtype exact "orcid_pending")';
        this.showLoading = false;
      },
      error => {
        this.handleError("Could not get user's ORCID iD", error);
        this.showLoading = false;
      }
    ));

    this.subscriptions.push(this.route.queryParams.subscribe(params => {
      this.parameters = Object.assign({}, params);
      this.keyword = params["fv0"]?params["fv0"]:'';
    }));
  }

  public ngOnDestroy() {
    for(let sub of this.subscriptions){
      sub.unsubscribe();
    }
  }
  keywordChanged() {

    if (this.keyword.length > 0) {
      this.parameters["fv0"] = this.keyword;
      this.parameters["f0"] = "q";
    } else {
      delete this.parameters['fv0'];
      delete this.parameters['f0'];
    }

    if (this.parameters["page"]) {
      //GO to first page
      delete this.parameters['page'];
    }

    this.router.navigate(['/recommended-orcid-links'], {queryParams: this.parameters});
  }

  private handleError(message: string, error) {
    console.error("Search My Results in Orcid Page: "+message, error);
  }
}
