
import { FormGroup, Validators } from '@angular/forms';
import { FieldSet } from '../../../../core/model/admin/dataset-profile/dataset-profile';
import { BaseFormModel } from '../../../../core/model/base-form-model';
import { FieldEditorModel } from './field-editor-model';
import { MultiplicityEditorModel } from './multiplicity-editor-model';

export class FieldSetEditorModel extends BaseFormModel {

	public fields: Array<FieldEditorModel> = new Array<FieldEditorModel>();
	public id: string;
	public ordinal: number;
	public multiplicity: MultiplicityEditorModel = new MultiplicityEditorModel();
	public title: string;
	public description: string;
	public extendedDescription: string;
	public additionalInformation: string;
	public hasCommentField: boolean;

	fromModel(item: FieldSet): FieldSetEditorModel {

		if (item.fields) { this.fields = item.fields.map(x => new FieldEditorModel().fromModel(x)); }
		if (item.multiplicity) this.multiplicity = new MultiplicityEditorModel().fromModel(item.multiplicity);
		this.id = item.id;
		this.ordinal = item.ordinal;
		this.title = item.title;
		this.description = item.description;
		this.extendedDescription = item.extendedDescription;
		this.additionalInformation = item.additionalInformation;
		this.hasCommentField = item.hasCommentField;
		return this;
	}

	buildForm(disabled: boolean = false, skipDisable: Array<String> = []): FormGroup {
		const formGroup = this.formBuilder.group({
			id: [{ value: this.id, disabled: (disabled && !skipDisable.includes('FieldSetEditorModel.id')) }, [Validators.required, Validators.pattern('^[^<_>]+$')]],
			ordinal: [{ value: this.ordinal, disabled: (disabled && !skipDisable.includes('FieldSetEditorModel.ordinal')) }],
			title: [{ value: this.title, disabled: (disabled && !skipDisable.includes('FieldSetEditorModel.title')) }, [Validators.required]],
			description: [{ value: this.description, disabled: (disabled && !skipDisable.includes('FieldSetEditorModel.description')) }],
			extendedDescription: [{ value: this.extendedDescription, disabled: (disabled && !skipDisable.includes('FieldSetEditorModel.extendedDescription')) }],
			additionalInformation: [{ value: this.additionalInformation, disabled: (disabled && !skipDisable.includes('FieldSetEditorModel.additionalInformation')) }],
			hasCommentField: [{ value: this.hasCommentField, disabled: (disabled && !skipDisable.includes('FieldSetEditorModel.hasCommentField')) }]
		});
		const fieldsFormArray = new Array<FormGroup>();
		this.fields.forEach(item => {
			const form: FormGroup = item.buildForm(disabled, skipDisable);
			fieldsFormArray.push(form);
		});
		formGroup.addControl('fields', this.formBuilder.array(fieldsFormArray));
		formGroup.addControl('multiplicity', this.multiplicity.buildForm(disabled, skipDisable));

		return formGroup;
	}
}
