import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Status } from '@app/core/common/enum/status';
import { GrantListingModel } from '@app/core/model/grant/grant-listing';
import { ValidJsonValidator } from '@app/library/auto-complete/auto-complete-custom-validator';
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 GrantTabModel {
	public id: string;
	public label?: string;
	public status: Status = Status.Active;
	public description: String;
	public existGrant: GrantListingModel;
	public funderId: String;
	public validationErrorModel: ValidationErrorModel = new ValidationErrorModel();
	public reference: string;


	fromModel(item: GrantListingModel): GrantTabModel {
		this.existGrant = item;
		return this;
	}

	buildForm(context: ValidationContext = null, disabled: boolean = false): FormGroup {
		if (context == null) { context = this.createValidationContext(); }

		const formGroup = new FormBuilder().group({
			id: [{ value: this.id, disabled: disabled }, context.getValidation('id').validators],
			label: [{ value: this.label, disabled: disabled }, context.getValidation('label').validators],
			status: [{ value: this.status, disabled: disabled }, context.getValidation('status').validators],
			description: [{ value: this.description, disabled: disabled }, context.getValidation('description').validators],
			existGrant: [{ value: this.existGrant, disabled: disabled }, context.getValidation('existGrant').validators],
			funderId: [{ value: this.funderId, disabled: disabled }, context.getValidation('funderId').validators],
			reference: [{ value: this.funderId, disabled: disabled }, context.getValidation('reference').validators],
		});
		return formGroup;
	}

	createValidationContext(): ValidationContext {
		const baseContext: ValidationContext = new ValidationContext();
		baseContext.validation.push({ key: 'id', validators: [] });
		baseContext.validation.push({ key: 'label', validators: [Validators.required, BackendErrorValidator(this.validationErrorModel, 'label')] });
		baseContext.validation.push({ key: 'status', validators: [] });
		baseContext.validation.push({ key: 'description', validators: [Validators.required, BackendErrorValidator(this.validationErrorModel, 'description')] });
		baseContext.validation.push({ key: 'existGrant', validators: [Validators.required, ValidJsonValidator, BackendErrorValidator(this.validationErrorModel, 'existGrant')] });
		baseContext.validation.push({ key: 'funderId', validators: [ValidJsonValidator, BackendErrorValidator(this.validationErrorModel, 'funderId')] });
		baseContext.validation.push({ key: 'reference', validators: [BackendErrorValidator(this.validationErrorModel, 'reference')] });
		return baseContext;
	}


}

