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

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

	constructor(
		private externalDatasetService: ExternalDatasetService,
		public dialogRef: MatDialogRef<DatasetExternalDatasetDialogEditorComponent>,
		@Inject(MAT_DIALOG_DATA) public data: any,
		private formService: FormService
	) { super(); }

	ngOnInit(): void {
		const externalDatasetModel = new ExternalDatasetEditorModel();
		this.formGroup = externalDatasetModel.buildForm();
	}

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

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