import { Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges } from '@angular/core';

import { FormControl, FormGroup } from '@angular/forms';
import { DynamicFormConfig } from 'common/ui/dynamicform/DynamicFormConfig';

declare let $;
declare let _;

@Component({
	selector: 'dynamic-form-component',
	templateUrl: './DynamicFormComponent.html',
	styleUrls: ['./DynamicFormComponent.ng.pcss']
})
export class DynamicFormComponent implements OnInit, OnChanges {
	@Input()
	config: DynamicFormConfig;

	@Input()
	patchValue: { [key: string]: any } = {};

	@Output()
	submitted = new EventEmitter();

	form: FormGroup;

	constructor() {
	}

	ngOnInit(): void {
		this.buildForm();
	}

	ngOnChanges(changes: SimpleChanges): void {
		if (this.form && this.patchValue) 

	}

	submit(event: any) {
		event.preventDefault();

		if (!this.form.valid) {
			console.log('form invalid');
			return;
		}

		this.submitted.emit(this.form.value)
	}

	public patchForm(obj: { [key: string]: any; }) {
		let values = {};
		_.forEach(obj, (value, key) => {
			values[key] = value;
		});

		this.form.patchValue(values);
	}

	private buildForm() {
		let group = {};
		let patchValue = {};
		_.forEach(this.config.controls, (control) => {
			group[control.key] = new FormControl(control.value, control.validator);
			patchValue[control.key] = control.value;
		});

		this.form = new FormGroup(group);
	}
}
{
			this.patchForm(this.patchValue)
		}