import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroupDirective, NgForm } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';
import { GrantStateType } from '@app/core/common/enum/grant-state-type';
import { GrantCriteria } from '@app/core/query/grant/grant-criteria';
import { BaseCriteriaComponent } from '@app/ui/misc/criteria/base-criteria.component';
import { ValidationErrorModel } from '@common/forms/validation/error-model/validation-error-model';
import { TranslateService } from '@ngx-translate/core';

@Component({
	selector: 'app-grant-criteria-component',
	templateUrl: './grant-criteria.component.html',
	styleUrls: ['./grant-criteria.component.scss']
})
export class GrantCriteriaComponent extends BaseCriteriaComponent implements OnInit, ErrorStateMatcher {

	public GrantStateType = GrantStateType;
	public criteria: GrantCriteria = new GrantCriteria();

	constructor(
		public language: TranslateService,
		public formBuilder: FormBuilder
	) {
		super(new ValidationErrorModel());
	}

	ngOnInit() {
		super.ngOnInit();
		if (this.criteria == null) {
			this.criteria = new GrantCriteria();
			this.criteria.grantStateType = GrantStateType.OnGoing;
		}
	}

	setCriteria(criteria: GrantCriteria): void {
		this.criteria = criteria;
	}

	onCallbackError(error: any) {
		this.setErrorModel(error.error);
	}

	controlModified(): void {
		this.clearErrorModel();
		if (this.refreshCallback != null &&
			(this.criteria.like == null || this.criteria.like.length === 0 || this.criteria.like.length > 2)
		) {
			setTimeout(() => this.refreshCallback(true));
		}
	}

	isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
		const isSubmitted = form && form.submitted;
		const isDateInvalid = this.criteria.periodStart != null && this.criteria.periodEnd != null && this.criteria.periodStart > this.criteria.periodEnd
		return !!(control && isDateInvalid && (control.dirty || control.touched || isSubmitted));
	}
}
