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';

import { LanguageService } from '../../language.service';
import { LanguageData } from '../../language.model';

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

export class ItemEditComponent implements OnInit {

	form: UntypedFormGroup;
	id: string | undefined = '';
	numberRegEx = /\d*\.?\d{1,2}/;
    //
    // Language Support
    //
    vE = {
    	itemeditCloseBtn : '',
    	itemeditEditItem : '',
    	itemeditItemDescr : '',
    	itemeditItemLabel : '',
    	itemeditItemPrice : '',
    	itemeditSaveBtn : ''
    }
    //
    // ------------------------------------------------------------
	constructor(
		private languageService : LanguageService,
		private fb: UntypedFormBuilder,
		private dialogRef: MatDialogRef<ItemEditComponent>,
		@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 () {
        this.chgUILanguage();
	}

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

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

	chgUILanguage(){
        console.log('ITEMEDIT.chgUILanguage Called ');
 		this.languageService.getViewElements('itemedit').subscribe(
				response => { 
					console.log('Received >> ', response );
					console.log('Language Code : ', response.language);
					console.log('Component Name : ',response.component);
					console.log('Language data : ',response.data);

			        this.vE.itemeditEditItem = response.data.itemedit_edit_item;
			        this.vE.itemeditItemLabel = response.data.itemedit_item_label;
			    	this.vE.itemeditItemDescr = response.data.itemedit_item_descr;
			    	this.vE.itemeditItemPrice = response.data.itemedit_item_price;
			    	this.vE.itemeditCloseBtn = response.data.itemedit_close_btn;
			    	this.vE.itemeditSaveBtn = response.data.itemedit_save_btn;
			    },
				error  => { console.log('Error >> ',error); }
			);
	}

}
