import { Component, Inject, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { ExternalServiceService } from '@app/core/services/external-sources/service/external-service.service';
import { ExternalServiceEditorModel } 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-service-dialog-editor.component.html',
	styleUrls: ['./dataset-external-service-dialog-editor.component.scss']
})
export class DatasetExternalServiceDialogEditorComponent extends BaseComponent implements OnInit {
	public formGroup: FormGroup;

	constructor(
		private externalServiceService: ExternalServiceService,
		public dialogRef: MatDialogRef<DatasetExternalServiceDialogEditorComponent>,
		@Inject(MAT_DIALOG_DATA) public data: any,
		private formService: FormService
	) { super(); }

	ngOnInit(): void {
		const serviceModel = new ExternalServiceEditorModel();
		this.formGroup = serviceModel.buildForm();
	}

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

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