
import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { DataTableRequest } from '@app/core/model/data-table/data-table-request';
import { GrantListingModel } from '@app/core/model/grant/grant-listing';
import { DatasetProfileCriteria } from '@app/core/query/dataset-profile/dataset-profile-criteria';
import { DmpCriteria } from '@app/core/query/dmp/dmp-criteria';
import { GrantCriteria } from '@app/core/query/grant/grant-criteria';
import { OrganisationCriteria } from '@app/core/query/organisation/organisation-criteria';
import { UserCriteria } from '@app/core/query/user/user-criteria';
import { DatasetProfileService } from '@app/core/services/dataset-profile/dataset-profile.service';
import { DmpService } from '@app/core/services/dmp/dmp.service';
import { GrantService } from '@app/core/services/grant/grant.service';
import { OrganisationService } from '@app/core/services/organisation/organisation.service';
import { UserService } from '@app/core/services/user/user.service';
import { MultipleAutoCompleteConfiguration } from '@app/library/auto-complete/multiple/multiple-auto-complete-configuration';
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';
import { map, takeUntil } from 'rxjs/operators';
import { AuthService } from '@app/core/services/auth/auth.service';
import { isNullOrUndefined } from '@app/utilities/enhancers/utils';
import { DatasetService } from '@app/core/services/dataset/dataset.service';
import { DatasetProfileModel } from '@app/core/model/dataset/dataset-profile';
import { Observable } from 'rxjs';

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

	@Input() showGrant: boolean;
	@Input() isPublic: boolean;
	@Input() criteriaFormGroup: FormGroup;
	@Output() filtersChanged: EventEmitter<any> = new EventEmitter();

	filteringGrantsAsync = false;
	sizeError = false;
	maxFileSize: number = 1048576;
	filteringOrganisationsAsync = false;

	filteredGrants: GrantListingModel[];
	public formGroup = new FormBuilder().group({
		like: new FormControl(),
		grants: new FormControl(),
		status: new FormControl(),
		role: new FormControl,
		organisations: new FormControl(),
		collaborators: new FormControl(),
		datasetTemplates: new FormControl(),
		grantStatus: new FormControl()
	});

	collaboratorsAutoCompleteConfiguration: MultipleAutoCompleteConfiguration = {
		filterFn: this.filterCollaborators.bind(this),
		initialItems: (excludedItems: any[]) => this.filterCollaborators('').pipe(map(result => result.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1))),
		displayFn: (item) => item['name'],
		titleFn: (item) => item['name']
	};

	datasetTemplateAutoCompleteConfiguration: MultipleAutoCompleteConfiguration = {
		filterFn: this.filterDatasetTemplate.bind(this),
		initialItems: (excludedItems: any[]) => this.filterDatasetTemplate('').pipe(map(result => result.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1))),
		displayFn: (item) => item['label'],
		titleFn: (item) => item['label'],
		subtitleFn: (item) => item['description']
	};

	grantAutoCompleteConfiguration: MultipleAutoCompleteConfiguration = {
		filterFn: this.filterGrant.bind(this),
		initialItems: (excludedItems: any[]) => this.filterGrant('').pipe(map(result => result.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1))),
		displayFn: (item) => item['label'],
		titleFn: (item) => item['label']
	};

	organisationAutoCompleteConfiguration: MultipleAutoCompleteConfiguration = {
		filterFn: this.filterOrganisations.bind(this),
		initialItems: (excludedItems: any[]) => this.filterOrganisations('').pipe(map(result => result.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1))),
		displayFn: (item) => item['name'],
		titleFn: (item) => item['name']
	}

	constructor(
		public language: TranslateService,
		public grantService: GrantService,
		private dmpService: DmpService,
		public formBuilder: FormBuilder,
		private dialog: MatDialog,
		private organisationService: OrganisationService,
		private userService: UserService,
		private datasetProfileService: DatasetService,
		private authService: AuthService
	) {
		super(new ValidationErrorModel());
	}

	ngOnInit() {
		super.ngOnInit();

		// This if is just for passing label on chips of dialog
		if (this.formGroup && this.criteriaFormGroup) {
			this.formGroup.get('datasetTemplates').setValue(this.criteriaFormGroup.get('datasetTemplates').value);
			this.formGroup.get('grants').setValue(this.criteriaFormGroup.get('grants').value);
			this.formGroup.get('collaborators').setValue(this.criteriaFormGroup.get('collaborators').value);
			this.formGroup.get('organisations').setValue(this.criteriaFormGroup.get('organisations').value);
			this.formGroup.get('status').setValue(this.criteriaFormGroup.get('status').value);
		}

		this.formGroup.get('role').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => this.controlModified());
		this.formGroup.get('organisations').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => this.controlModified());
		this.formGroup.get('status').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => this.controlModified());
		this.formGroup.get('grants').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => this.controlModified());
		this.formGroup.get('like').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => this.controlModified());
		this.formGroup.get('collaborators').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => this.controlModified());
		this.formGroup.get('datasetTemplates').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => this.controlModified());
		this.formGroup.get('grantStatus').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => this.controlModified());
		//if (this.criteria == null) { this.criteria = new DataManagementPlanCriteria(); }
	}

	setCriteria(criteria: DmpCriteria): void {
		this.formGroup.get('like').patchValue(criteria.like);
		this.formGroup.get('grants').patchValue(criteria.grants);
		this.formGroup.get('status').patchValue(criteria.status);
		this.formGroup.get('role').patchValue(criteria.role);
		this.formGroup.get('collaborators').patchValue(criteria.collaborators);
		this.formGroup.get('datasetTemplates').patchValue(criteria.datasetTemplates);
		this.formGroup.get('grantStatus').patchValue(criteria.grantStatus);
		this.formGroup.get('organisations').patchValue(criteria.organisations);
	}

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

	controlModified(): void {
		this.clearErrorModel();
		this.filtersChanged.emit();
		if (this.refreshCallback != null &&
			(this.formGroup.get('like').value == null || this.formGroup.get('like').value.length === 0 || this.formGroup.get('like').value.length > 2)
		) {
			setTimeout(() => this.refreshCallback(true));
		}
	}

	filterGrant(query: string) {
		const fields: Array<string> = new Array<string>();
		fields.push('asc');
		const grantRequestItem: DataTableRequest<GrantCriteria> = new DataTableRequest(0, null, { fields: fields });
		grantRequestItem.criteria = new GrantCriteria();
		grantRequestItem.criteria.like = query;
		return this.isPublic ? this.grantService.getPublicPaged(grantRequestItem).pipe(map(x => x.data)) : this.grantService.getPaged(grantRequestItem, "autocomplete").pipe(map(x => x.data));
	}

	filterOrganisations(value: string) {
		this.filteringOrganisationsAsync = true;
		const fields: Array<string> = new Array<string>();
		fields.push('asc');
		const dataTableRequest: DataTableRequest<OrganisationCriteria> = new DataTableRequest(0, null, { fields: fields });
		dataTableRequest.criteria = new OrganisationCriteria();
		dataTableRequest.criteria.labelLike = value;

		return this.isPublic ? this.organisationService.searchPublicOrganisations(dataTableRequest).pipe(map(x => x.data)) : this.organisationService.searchInternalOrganisations(dataTableRequest).pipe(map(x => x.data));
	}

	filterCollaborators(query: string) {
		const fields: Array<string> = new Array<string>();
		fields.push('asc');
		const collaboratorsRequestItem: DataTableRequest<UserCriteria> = new DataTableRequest(0, null, { fields: fields });
		collaboratorsRequestItem.criteria = new UserCriteria();
		collaboratorsRequestItem.criteria.collaboratorLike = query;
		return this.userService.getCollaboratorsPaged(collaboratorsRequestItem).pipe(map(x => x.data));
	}

	filterDatasetTemplate(query: string): Observable<any> {
		const fields: Array<string> = new Array<string>();
		fields.push('+label');
		const datasetTemplateRequestItem: DataTableRequest<DatasetProfileCriteria> = new DataTableRequest(0, null, { fields: fields });
		datasetTemplateRequestItem.criteria = new DatasetProfileCriteria();
		datasetTemplateRequestItem.criteria.like = query;
		return this.isPublic ? this.datasetProfileService.getDatasetProfiles(datasetTemplateRequestItem) : this.dmpService.getDatasetProfilesUsedPaged(datasetTemplateRequestItem).pipe(map(x => x.data));
	}

	isAuthenticated(): boolean {
		return !isNullOrUndefined(this.authService.current());
	}


}
