import { Component, Input, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { DatasetProfileInternalDmpEntitiesType } from '@app/core/common/enum/dataset-profile-internal-dmp-entities-type';
import { EnumUtils } from '@app/core/services/utilities/enum-utils.service';
import { DatasetsAutoCompleteFieldDataEditorModel } from '@app/ui/admin/dataset-profile/admin/field-data/datasets-autocomplete-field-data-editor-mode';
import { DmpsAutoCompleteFieldDataEditorModel } from '@app/ui/admin/dataset-profile/admin/field-data/dmps-autocomplete-field-data-editor-model';
import { ResearchersAutoCompleteFieldDataEditorModel } from '@app/ui/admin/dataset-profile/admin/field-data/researchers-auto-complete-field-data-editor-model';
import { BaseComponent } from '@common/base/base.component';
import { takeUntil } from 'rxjs/operators';

@Component({
	selector: 'app-dataset-profile-internal-dmp-entities-field-component',
	styleUrls: ['./dataset-profile-editor-internal-dmp-entities-field.component.scss'],
	templateUrl: './dataset-profile-editor-internal-dmp-entities-field.component.html'
})
export class DatasetProfileEditorInternalDmpEntitiesFieldComponent extends BaseComponent implements OnInit {
	@Input() form: FormGroup;
	options = DatasetProfileInternalDmpEntitiesType;

	constructor(
		public enumUtils: EnumUtils
	) { super() }

	ngOnInit() {
		this.setupListeners();
	}

	setupListeners() {
		this.form.get('data').get('type').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => {
				if (this.form.get('data')) { this.form.removeControl('data'); }
				if (x === DatasetProfileInternalDmpEntitiesType.Researchers) {
					this.form.addControl('data', new ResearchersAutoCompleteFieldDataEditorModel().buildForm());
				} else if (x === DatasetProfileInternalDmpEntitiesType.Datasets) {
					this.form.addControl('data', new DatasetsAutoCompleteFieldDataEditorModel().buildForm());
				}
				else if (x === DatasetProfileInternalDmpEntitiesType.Dmps) {
					this.form.addControl('data', new DmpsAutoCompleteFieldDataEditorModel().buildForm());
				}
				this.setupListeners();
			})
	}
}
