import {Component, Input, Output, EventEmitter, ViewChild} from '@angular/core';
import {Observable} from 'rxjs';
import {Router, ActivatedRoute} from '@angular/router';
import {ClaimsService} from '../../claim-utils/service/claims.service';
import {ModalLoading} from '../../../utils/modal/loading.component';
import {AlertModal} from '../../../utils/modal/alert';
import {Md5} from 'ts-md5/dist/md5';
import {Session} from '../../../login/utils/helper.class';
import {LoginErrorCodes} from '../../../login/utils/guardHelper.class';
import{EnvProperties} from '../../../utils/properties/env-properties';
@Component({
selector: 'claim-insert',
template: `
0">
0">{{insertedClaims.length | number}} claims created, follow the link to manage your claims
0">
{{warningMessage}}
`
})
export class ClaimInsertComponent {
constructor (private claimService: ClaimsService, private _router:Router, private route: ActivatedRoute,) {}
ngOnInit() {
this.route.queryParams.subscribe(params => {
this.params = params;
});
// console.info("Inlineentity:" +(this.inlineEntity)?this.inlineEntity+(this.inlineEntity.id)?this.inlineEntity.id:"no id":"null"+ + " show "+ (!this.claiming && this.showButton) );
}
params= {};
@Input() public contexts;
@Input() public projects;
@Input() public results;
@Input() public showButton:boolean = true;
@Input() show='claim';
@Input() inlineEntity = null; // the entity from the landing page
@Input() public properties:EnvProperties;
@Output() showChange = new EventEmitter();
@Input() localStoragePrefix:string="";
@ViewChild (ModalLoading) loading : ModalLoading ;
@ViewChild(AlertModal) alert;
public claiming =false;
public error = false;
public errorMessage = "";
public warningMessage = "";
public claimsTODO:number = 0;
public claims:number = 0;
private servicesRespond:number = 0;
private insertedClaims=[];
private errorInClaims=[];
private insertedRecords=[];
private errorInRecords=[];
public validateInsertions(){
// console.info("Inlineentity:" +(this.inlineEntity)?this.inlineEntity+(this.inlineEntity.id)?this.inlineEntity.id:"no id":"null"+ + " show "+ (!this.claiming && this.showButton) );
if(this.validate()){
if(this.validateDates()){
this.insertActions();
return true;
}
}
return false;
}
private insertActions(){
this.servicesRespond = 0;
this.insertedClaims=[];
this.errorInClaims=[];
this.insertedRecords=[];
this.errorInRecords=[];
if(!Session.isLoggedIn()){
this.showButton = false;
localStorage.setItem(this.localStoragePrefix + "projects", JSON.stringify(this.projects));
localStorage.setItem(this.localStoragePrefix + "contexts", JSON.stringify(this.contexts));
localStorage.setItem(this.localStoragePrefix + "results", JSON.stringify(this.results));
if(this.inlineEntity != null){
localStorage.setItem(this.localStoragePrefix + "inlineEntity", JSON.stringify(this.inlineEntity));
}
this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url} });
}else{
this.claiming = true;
var user=Session.getUserEmail();
this.loading.open();
var claims = [];
var directclaims = [];
if(this.results ){
for (var i = 0; i < this.results.length; i++) {
var result=this.results[i];
if(["crossref","datacite","orcid"].indexOf(result.source) != -1){
directclaims.push({"id":result.id, "record":this.createDirectClaim(result,this.projects,this.contexts)});
}
if(this.contexts){
for (var j = 0; j < this.contexts.length; j++) {
var context = this.contexts[j];
var claim = this.createContextClaim(result, context, user);
claims.push(claim);
}
}
if(this.projects){
for (var k = 0; k < this.projects.length; k++) {
var project = this.projects[k];
var projectClaim = this.createProjectClaim(result, project, user);
claims.push(projectClaim);
}
}
if(this.inlineEntity != null){
var resultClaim = this.createResultClaim(this.inlineEntity, result, user);
claims.push(resultClaim);
}
}
}
if(this.inlineEntity ){
if(this.contexts){
for (var j = 0; j < this.contexts.length; j++) {
var context = this.contexts[j];
var claim = this.createContextClaim(this.inlineEntity, context, user);
claims.push(claim);
}
}
if(this.projects){
for (var k = 0; k < this.projects.length; k++) {
var project = this.projects[k];
var projectClaim = this.createProjectClaim(this.inlineEntity, project, user);
claims.push(projectClaim);
}
}
}
//first call direct index service - when call is done (success or error) call isertBulkClaims method to insert claims in DB
if(directclaims.length > 0){
this.claimService.insertDirectRecords(directclaims,this.properties.claimsAPIURL).subscribe(
data => {
this.insertedRecords = data.insertedIds;
this.errorInRecords = data.errorInClaims;
this.isertBulkClaims(claims);
},
err => {
err=err.json();
if(err.insertedIds && err.insertedIds.length >0){
this.insertedRecords = err.insertedIds;
}
if(err.errorInClaims && err.errorInClaims.length >0){
this.errorInRecords = err.errorInClaims;
}
this.isertBulkClaims(claims);
this.handleError("Error inserting direct records: "+JSON.stringify(directclaims), err);
}
);
}else{
this.isertBulkClaims(claims);
}
}
}
private isertBulkClaims(claims){
this.claimService.insertBulkClaims(claims,this.properties.claimsAPIURL).subscribe(
data => {
this.insertedClaims = data.insertedIds;
this.errorInClaims = data.errorInClaims;
this.afterclaimsInsertion();
},
err => {
err=err.json();
if(err.insertedIds && err.insertedIds.length >0){
this.insertedClaims = err.insertedIds;
}
if(err.errorInClaims && err.errorInClaims.length >0){
this.errorInClaims = err.errorInClaims;
}
if(this.projects != null){
localStorage.setItem(this.localStoragePrefix + "projects", JSON.stringify(this.projects));
}
localStorage.setItem(this.localStoragePrefix + "contexts", JSON.stringify(this.contexts));
if(this.results != null){
localStorage.setItem(this.localStoragePrefix + "results", JSON.stringify(this.results));
}
if(this.inlineEntity != null){
localStorage.setItem(this.localStoragePrefix + "inlineEntity", JSON.stringify(this.inlineEntity));
}
this.afterclaimsInsertion();
this.handleError("Error inserting bulk claims: "+JSON.stringify(claims), err);
}
);
}
private validate(){
this.warningMessage = "";
this.errorMessage = "";
if( this.results && this.results.length == 0 && ( this.inlineEntity == null)){
this.warningMessage = "There are no research results selected.";
}else if((!this.contexts|| this.contexts.length==0 )&&(!this.projects|| this.projects.length==0 )&& ( this.inlineEntity == null)){
this.warningMessage = "There are no projects or communities to link.";
// }else if (this.inline && !this.inlineEntity){
// this.errorMessage = "No inline entity";
// console.log(this.inline + " "+ this.inlineEntity);
}else{
return true;
}
return false;
}
private validateDates(){
if(this.projects){
for (var k = 0; k < this.projects.length; k++) {
var project = this.projects[k];
if(this.results){
for (var i = 0; i < this.results.length; i++) {
var result = this.results[i];
if(result.date && result.date != null){
if((project.startDate && result.date < project.startDate) || ( project.endDate && result.date > (project.endDate+5)) ){
this.confirmOpen();
return false;
}
}
}
}
}
}
if(this.results){
for (var i = 0; i < this.results.length; i++) {
var result = this.results[i];
if(result.date && result.date != null){
if((result.embargoEndDate && result.embargoEndDate != null) && result.date >result.embargoEndDate ){
this.confirmOpen();
return false;
}
}
}
}
return true;
}
private afterclaimsInsertion(){
this.loading.close();
this.claiming = false;
if(this.errorInClaims.length == 0 && this.insertedClaims.length > 0 && this.errorInRecords.length == 0){
localStorage.removeItem(this.localStoragePrefix + "projects");
localStorage.removeItem(this.localStoragePrefix + "contexts");
localStorage.removeItem(this.localStoragePrefix + "results");
this._router.navigate( ['/myclaims'],{ queryParams: this.params } );
this.showChange.emit({
value: this.show
});
}else{
this.errorsInClaimsInsertion();
}
}
private errorsInClaimsInsertion(){
this.errorMessage = "";
this.loading.close();
this.error = true;
this.claiming = false;
this.showButton = false;
var text =""
//console.log("Errors: this.errorInRecords.length: "+this.errorInRecords.length+" - this.errorInClaims.length: "+this.errorInClaims.length);
if(this.errorInRecords.length>0){
text+="
The following results couldn't automatically inserted to the Openaire Info space:
"+this.errorInClaims[i].sourceType+": "+this.errorInClaims[i].sourceId +" ("+this.errorInClaims[i].sourceCollectedFrom+") link to "+this.errorInClaims[i].targetType+": "+this.errorInClaims[i].targetId +" ("+this.errorInClaims[i].targetCollectedFrom+")