import { Component, Input, OnInit } from '@angular/core';
import { FormArray, FormControl, FormGroup } from '@angular/forms';
import { FieldEditorModel } from '../../../admin/field-editor-model';
import { Guid } from '@common/types/guid';

@Component({
	selector: 'app-dataset-profile-editor-composite-field-component',
	templateUrl: './dataset-profile-editor-composite-field.component.html',
	styleUrls: ['./dataset-profile-editor-composite-field.component.scss']
})
export class DatasetProfileEditorCompositeFieldComponent implements OnInit {

	@Input() form: FormGroup;
	@Input() indexPath: string;
	@Input() viewOnly: boolean;

	isComposite = false;
	isMultiplicityEnabled = false;

	constructor() { }

	ngOnInit() {
		//this.addNewField();
		if (this.form.get('multiplicity')) {
			if (this.form.get('multiplicity').value.min > 1 || this.form.get('multiplicity').value.max > 1) {
				this.isMultiplicityEnabled = true;
			}
		}
		this.isComposite = (this.form.get('fields') as FormArray).length > 1;

		if (this.viewOnly) {
			this.form.get('hasCommentField').disable();
		}
	}

	onIsCompositeChange(isComposite: boolean) {
		if (!isComposite && (<FormArray>this.form.get('fields')).length > 1) {
			for (let i = 0; i < (<FormArray>this.form.get('fields')).length - 1; i++) {
				(<FormArray>this.form.get('fields')).removeAt(1);
			}
			(this.form.get('fields') as FormArray).controls.splice(1);
		}
		if ((<FormArray>this.form.get('fields')).length === 0) {
			const field: FieldEditorModel = new FieldEditorModel();
			(<FormArray>this.form.get('fields')).push(field.buildForm());
		}
	}

	onIsMultiplicityEnabledChange(isMultiplicityEnabled: boolean) {
		if (!isMultiplicityEnabled) {
			(<FormControl>this.form.get('multiplicity').get('min')).setValue(0);
			(<FormControl>this.form.get('multiplicity').get('max')).setValue(0);
		}
	}

	addNewField() {
		const field: FieldEditorModel = new FieldEditorModel();
		field.id=Guid.create().toString();
		(<FormArray>this.form.get('fields')).push(field.buildForm());
	}

	DeleteField(index) {
		(<FormArray>this.form.get('fields')).removeAt(index);
	}

	getFieldTile(formGroup: FormGroup, index: number) {
		if (formGroup.get('title') && formGroup.get('title').value && formGroup.get('title').value.length > 0) { return formGroup.get('title').value; }
		return "Field " + (index + 1);
	}
}
