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 { OrganisationService } from '@app/core/services/organisation/organisation.service';
import { BaseComponent } from '@common/base/base.component';
import { Observable } from 'rxjs';
import { debounceTime, distinctUntilChanged, first, map, mergeMap, takeUntil } from 'rxjs/operators';
import { OrganizationEditorModel } from './add-organization.model';

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

	public formGroup: FormGroup;

	private readonly _REFERENCE_PREFIX:string = "Internal:";
	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<AddOrganizationComponent>,
		private organizationService: OrganisationService,
		@Inject(MAT_DIALOG_DATA) public data: any
	) { 
		super(); 
		if(data){
			const organisations = (data as FormControl).value ;
			if(organisations){
				this.existingReferences = (organisations as Array<any>).map(organisation => organisation.reference);
			}
		}}

	ngOnInit(): void {
		const researcher = new OrganizationEditorModel();
		this.formGroup = researcher.buildForm();
		this.formGroup.get('reference').setAsyncValidators(this.organizationUniqueIdentifier());
	}

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

	addOrganization() {
		this.dialogRef.close(this.formGroup.value);
	}

	isFormValid() {
		return this.formGroup.valid && !this.referenceExists;
	}
	private organizationUniqueIdentifier(): AsyncValidatorFn{
		return (control: AbstractControl) :Observable<ValidationErrors | null> =>{
			return	control.valueChanges.pipe(
					debounceTime(600),
					mergeMap(value=>this.organizationService.searchGeneralOrganisations({criteria:{labelLike:'', like: this._REFERENCE_PREFIX +value}})),
					takeUntil(this._destroyed),
					map((response)=>{
						if(response && response.length){
							const internalOrganizations = (response as Array<any>).filter(organization=> organization.key === this._KEY).filter(organization=> organization.reference === this._REFERENCE_PREFIX + control.value);

							if(internalOrganizations && internalOrganizations.length){
								return {organizationIdentifierExists:true};
							}
						}
						return null;
					})
					
				).pipe(first())
			}
	}
}
