import { Component, Inject, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
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 { 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;

	constructor(
		private externalResearcherService: ExternalResearcherService,
		public dialogRef: MatDialogRef<AddResearcherComponent>,
		@Inject(MAT_DIALOG_DATA) public data: any
	) { super(); }

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

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

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

	isFormValid() {
		return this.formGroup.valid;
	}
}
