import { Component, Input, OnInit } from '@angular/core';
import { FormArray, FormGroup, AbstractControl } from '@angular/forms';
import { DatasetDescriptionCompositeFieldEditorModel, DatasetDescriptionFieldEditorModel } from '../../dataset-description-form.model';
import { ToCEntry } from '../../dataset-description.component';
import { VisibilityRulesService } from '../../visibility-rules/visibility-rules.service';

@Component({
	selector: 'app-form-composite-field',
	templateUrl: './form-composite-field.component.html',
	styleUrls: ['./form-composite-field.component.scss']
})
export class FormCompositeFieldComponent {

	@Input() datasetProfileId: String;
	@Input() form: FormGroup;
	@Input() isChild: Boolean = false;
	@Input() showDelete: Boolean = false;
	@Input() tocentry: ToCEntry;

	constructor(
		public visibilityRulesService: VisibilityRulesService,
		//private markForConsiderationService: MarkForConsiderationService,
	) {
	}

	ngOnInit() {

		if(this.tocentry){
			this.form = this.tocentry.form as FormGroup;
		}
	}

	// addMultipleField(fieldIndex: number) {
	// 	const compositeFieldToBeCloned = (this.form.get('compositeFields').get('' + fieldIndex) as FormGroup).getRawValue();
	// 	const compositeField: DatasetDescriptionCompositeFieldEditorModel = new DatasetDescriptionCompositeFieldEditorModel().cloneForMultiplicity(compositeFieldToBeCloned);
	// 	(<FormArray>(this.form.get('compositeFields').get('' + fieldIndex).get('multiplicityItems'))).push(compositeField.buildForm());
	// }

	// markForConsideration() {
	// 	this.markForConsiderationService.markForConsideration(this.compositeField);
	// }

	deleteCompositeField() {
		if (this.isChild) {
			this.deleteMultipeFieldFromCompositeFormGroup();
		} else {
			this.deleteCompositeFieldFormGroup();
		}
	}

	deleteCompositeFieldFormGroup() {
		const numberOfItems = this.form.get('multiplicityItems').get('' + 0).get('fields').value.length;
		for (let i = 0; i < numberOfItems; i++) {
			const multiplicityItem = this.form.get('multiplicityItems').get('' + 0).get('fields').get('' + i).value;
			this.form.get('fields').get('' + i).patchValue(multiplicityItem);
		}
		(<FormArray>(this.form.get('multiplicityItems'))).removeAt(0);
	}

	deleteMultipeFieldFromCompositeFormGroup() {
		const parent = this.form.parent;
		const index = (parent as FormArray).controls.indexOf(this.form);
		(parent as FormArray).removeAt(index);
		// (<FormArray>(this.form as AbstractControl)).removeAt(fildIndex);
	}
}
