import { Component, Inject, OnInit } from '@angular/core';
import { AbstractControl, AsyncValidatorFn, FormControl, FormGroup, ValidationErrors } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { ExternalSourcesService } from '@app/core/services/external-sources/external-sources.service';
import { ExternalResearcherService } from '@app/core/services/external-sources/researcher/external-researcher.service';
import { ResearcherEditorModel } from '@app/ui/dmp/editor/add-researcher/add-researcher.model';
import { BaseComponent } from '@common/base/base.component';
import { Observable } from 'rxjs';
import { debounceTime, distinctUntilChanged, filter, first, map, mergeMap, startWith, takeUntil } from 'rxjs/operators';

@Component({
	selector: 'app-add-researcher-component',
	templateUrl: 'add-researcher.component.html',
})
export class AddResearcherComponent extends BaseComponent implements OnInit {

	public formGroup: FormGroup;

	private readonly _REFERENCE_PREFIX:string = "dmp:";
	private readonly _KEY:string = 'Internal';
	private existingReferences: string[] = [];
	get referenceExists(){
		const reference  = this.formGroup.get('reference').value;
		
		return this.existingReferences.find((r)=>r === reference)
	}

	constructor(
		private externalSourcesService: ExternalSourcesService,
		private externalResearcherService: ExternalResearcherService,
		public dialogRef: MatDialogRef<AddResearcherComponent>,
		@Inject(MAT_DIALOG_DATA) public data: any
	) { super();
	
		if(data){
			const researchers = (data as FormControl).value ;
			if(researchers){
				this.existingReferences = (researchers as Array<any>).map(researcher => researcher.reference);
			}
		}
	}

	ngOnInit(): void {
		const researcher = new ResearcherEditorModel();
		this.formGroup = researcher.buildForm();

		this.formGroup.get('reference').setAsyncValidators(this.researcherUniqueIdentifier());
	}

	send(value: any) {
		this.externalResearcherService.createResearcher(this.formGroup.value)
			.pipe(takeUntil(this._destroyed))
			.subscribe(
				null, null, () => this.dialogRef.close()
			);
	}

	addResearcher() {

		const formValue = this.formGroup.value;
		formValue.reference = formValue.reference;
		this.dialogRef.close(this.formGroup.value);
	}

	isFormValid() {
		return this.formGroup.valid && !this.referenceExists;
	}

	private researcherUniqueIdentifier(): AsyncValidatorFn{
		return (control: AbstractControl) :Observable<ValidationErrors | null> =>{
			return	control.valueChanges.pipe(
					debounceTime(600),
					takeUntil(this._destroyed),
					mergeMap(value=>this.externalSourcesService.searchDMPResearchers({criteria:{name: '',like: null,reference: (this._REFERENCE_PREFIX + value) }})),
					map((response)=>{
						if(response && response.length){
							let internalEntries = (response as any[]).filter(record=>record.key === this._KEY);
							if(internalEntries && internalEntries.length){
								internalEntries = internalEntries.filter(record=> (record.reference === (this._REFERENCE_PREFIX + control.value)));
							}
							return internalEntries && internalEntries.length? {researcherIdentifierExists:true} : null;
						}
						return null;
					})
					
				).pipe(first())
			}
	}
}
