import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { AppRole } from '@app/core/common/enum/app-role';
import { UserCriteria } from '@app/core/query/user/user-criteria';
import { EnumUtils } from '@app/core/services/utilities/enum-utils.service';
import { BaseCriteriaComponent } from '@app/ui/misc/criteria/base-criteria.component';
import { ValidationErrorModel } from '@common/forms/validation/error-model/validation-error-model';
import { debounceTime, takeUntil } from 'rxjs/operators';

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

	public rolesEnum = this.enumUtils.getEnumValues(AppRole);
	public criteria: UserCriteria = new UserCriteria();

	constructor(
		private formBuilder: FormBuilder,
		public enumUtils: EnumUtils
	) {
		super(new ValidationErrorModel());
	}

	ngOnInit() {
		super.ngOnInit();
		if (this.criteria == null) { this.criteria = new UserCriteria(); }
		if (this.formGroup == null) { this.formGroup = this.buildForm(); }
		this.registerListeners();
	}

	setCriteria(criteria: UserCriteria): void {
		this.criteria = criteria;
		this.formGroup = this.buildForm();
		this.registerListeners();
	}

	registerListeners() {
		this.formGroup.valueChanges
			.pipe(takeUntil(this._destroyed), debounceTime(300))
			.subscribe(x => this.controlModified());
	}
	public fromJSONObject(item: any): UserCriteria {
		this.criteria = new UserCriteria();
		this.criteria.label = item.Label;
		this.criteria.appRoles = item.appRoles;
		return this.criteria;
	}

	buildForm(): FormGroup {
		return this.formBuilder.group({
			like: [this.criteria.label, []],
			appRoles: [this.criteria.appRoles, []],
		});
	}
}
