import {FormBuilder, FormGroup, ValidationErrors } from '@angular/forms';
import { ResearcherModel } from '@app/core/model/researcher/researcher';
import { BackendErrorValidator } from '@common/forms/validation/custom-validator';
import { ValidationErrorModel } from '@common/forms/validation/error-model/validation-error-model';
import { ValidationContext } from '@common/forms/validation/validation-context';

export class ResearcherEditorModel {
	public id: String;
	public name: String;
	public lastName: String;
	public uri: String;
	public email: String;
	public validationErrorModel: ValidationErrorModel = new ValidationErrorModel();
	public reference: String;


	fromModel(item: ResearcherModel): ResearcherEditorModel {
		this.id = item.id;
		this.name = item.name;
		this.email = item.email;
		this.uri = item.uri;
		this.reference  = item.reference;	
		return this;
	}

	buildForm(context: ValidationContext = null, disabled: boolean = false): FormGroup {
		if (context == null) { context = this.createValidationContext(); }
		const formGroup = new FormBuilder().group({
			reference: [{ value: this.reference, disabled: disabled },context.getValidation('reference')],
			firstName: [{ value: this.name, disabled: disabled }, context.getValidation('firstName').validators],
			lastName: [{ value: this.lastName, disabled: disabled }, context.getValidation('lastName').validators]
		});

		return formGroup;
	}

	createValidationContext(): ValidationContext {
		const baseContext: ValidationContext = new ValidationContext();
		baseContext.validation.push({ key: 'reference', validators: [BackendErrorValidator(this.validationErrorModel, 'reference')] });
		baseContext.validation.push({ key: 'firstName', validators: [BackendErrorValidator(this.validationErrorModel, 'firstName')] });
		baseContext.validation.push({ key: 'lastName', validators: [BackendErrorValidator(this.validationErrorModel, 'lastName')] });
		return baseContext;
	}
}
