import { Component, Inject, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { ExternalDataRepositoryService } from '@app/core/services/external-sources/data-repository/extternal-data-repository.service';
import { ExternalDataRepositoryEditorModel } from '@app/ui/dataset/dataset-wizard/dataset-wizard-editor.model';
import { BaseComponent } from '@common/base/base.component';
import { FormService } from '@common/forms/form-service';
import { takeUntil } from 'rxjs/operators';

@Component({
	templateUrl: 'dataset-external-data-repository-dialog-editor.component.html',
	styleUrls: ['./dataset-external-data-repository-dialog-editor.component.scss']
})
export class DatasetExternalDataRepositoryDialogEditorComponent extends BaseComponent implements OnInit {
	public formGroup: FormGroup;

	constructor(
		private externalDataRepositoryService: ExternalDataRepositoryService,
		public dialogRef: MatDialogRef<DatasetExternalDataRepositoryDialogEditorComponent>,
		@Inject(MAT_DIALOG_DATA) public data: any,
		private formService: FormService
	) { super(); }

	ngOnInit(): void {
		const datarepo = new ExternalDataRepositoryEditorModel();
		this.formGroup = datarepo.buildForm();
	}

	send(value: any) {
		this.formService.touchAllFormFields(this.formGroup);
		if (!this.formGroup.valid) { return; }
		this.externalDataRepositoryService.create(this.formGroup.value)
			.pipe(takeUntil(this._destroyed))
			.subscribe(
				(item) => this.dialogRef.close(item)
			);
	}

	close() {
		this.dialogRef.close(false);
	}
}
