import { Inject, Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { UntypedFormBuilder, Validators, UntypedFormGroup, UntypedFormControl } from '@angular/forms';
import { Item } from '../item.model';


@Component({
	selector: 'app-item-create',
	templateUrl: './item-create.component.html',
	styleUrls: ['./item-create.component.css']
})

export class ItemCreateComponent implements OnInit {

	form: UntypedFormGroup;
	id: string | undefined = '';
	numberRegEx = /\d*\.?\d{1,2}/;

	constructor(
		private fb: UntypedFormBuilder,
		private dialogRef: MatDialogRef<ItemCreateComponent>,
		@Inject(MAT_DIALOG_DATA) public data: Item
	){
		if (data._id === '') { 
			this.form = fb.group({
				id: [''],
				name: [null, Validators.required],
				description: [null, Validators.required],
				cost: new UntypedFormControl('', {
					validators: [Validators.required, Validators.pattern(this.numberRegEx)],
					updateOn: "blur"
				})
			});
		} else {
			this.id = data._id;
			this.form = fb.group({
				id: [data._id],
				name: [data.name, Validators.required],
				description: [data.description, Validators.required],
				cost: new UntypedFormControl(data.cost, {
					validators: [Validators.required, Validators.pattern(this.numberRegEx)],
					updateOn: "blur"
				})
			});
		}
	}

	ngOnInit () {
	}

	save() {
//		console.log(this.form.value);
		this.dialogRef.close(this.form.value);
	}

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