
import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';
import { Router } from '@angular/router';
import { DatasetStatus } from '@app/core/common/enum/dataset-status';
import { DataTableData } from '@app/core/model/data-table/data-table-data';
import { DataTableRequest } from '@app/core/model/data-table/data-table-request';
import { DmpListingModel } from '@app/core/model/dmp/dmp-listing';
import { ExternalSourceItemModel } from '@app/core/model/external-sources/external-source-item';
import { DatasetProfileCriteria } from '@app/core/query/dataset-profile/dataset-profile-criteria';
import { DatasetCriteria } from '@app/core/query/dataset/dataset-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 { RequestItem } from '@app/core/query/request-item';
import { TagCriteria } from '@app/core/query/tag/tag-criteria';
import { UserCriteria } from '@app/core/query/user/user-criteria';
import { DatasetWizardService } from '@app/core/services/dataset-wizard/dataset-wizard.service';
import { DatasetService } from '@app/core/services/dataset/dataset.service';
import { DmpService } from '@app/core/services/dmp/dmp.service';
import { ExternalSourcesService } from '@app/core/services/external-sources/external-sources.service';
import { GrantService } from '@app/core/services/grant/grant.service';
import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service';
import { OrganisationService } from '@app/core/services/organisation/organisation.service';
import { UserService } from '@app/core/services/user/user.service';
import { EnumUtils } from '@app/core/services/utilities/enum-utils.service';
import { MultipleAutoCompleteConfiguration } from '@app/library/auto-complete/multiple/multiple-auto-complete-configuration';
import { DatasetUploadDialogue } from '@app/ui/dataset/listing/criteria/dataset-upload-dialogue/dataset-upload-dialogue.component';
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 { Observable } from 'rxjs';
import { map, takeUntil } from 'rxjs/operators';
import { AuthService } from '@app/core/services/auth/auth.service';
import { isNullOrUndefined } from '@app/utilities/enhancers/utils';
import { ExploreDmpCriteriaModel } from '@app/core/query/explore-dmp/explore-dmp-criteria';
import { DatasetProfileModel } from '@app/core/model/dataset/dataset-profile';

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

	@Input() dmpSearchEnabled;
	@Input() status;
	@Input() isPublic: boolean;
	@Input() criteriaFormGroup: FormGroup;
	@Output() filtersChanged: EventEmitter<any> = new EventEmitter();
	public criteria: any;
	public filteringTagsAsync = false;
	public filteredTags: ExternalSourceItemModel[];
	statuses = DatasetStatus;

	options: FormGroup;

	public formGroup = new FormBuilder().group({
		like: new FormControl(),
		groupIds: new FormControl(),
		grants: new FormControl(),
		status: new FormControl(),
		role: new FormControl(),
		organisations: new FormControl(),
		collaborators: new FormControl(),
		datasetTemplates: new FormControl(),
		tags: new FormControl(),
		allVersions: new FormControl(),
		grantStatus: new FormControl()
	});

	tagsAutoCompleteConfiguration = {
		filterFn: this.filterTags.bind(this),
		initialItems: (excludedItems: any[]) => this.filterTags('').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']
	};

	dmpAutoCompleteConfiguration = {
		filterFn: (x, excluded) => this.filterDmps(x).pipe(map(x => x.data)),
		initialItems: (extraData) => this.filterDmps('').pipe(map(x => x.data)),
		displayFn: (item) => item['label'],
		titleFn: (item) => item['label']
	};

	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']
	};

	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(
		private externalSourcesService: ExternalSourcesService,
		public enumUtils: EnumUtils,
		public dmpService: DmpService,
		public datasetWizardService: DatasetWizardService,
		private dialog: MatDialog,
		private snackBar: MatSnackBar,
		private uiNotificationService: UiNotificationService,
		private router: Router,
		private language: TranslateService,
		public grantService: GrantService,
		private organisationService: OrganisationService,
		private userService: UserService,
		private datasetService: DatasetService,
		fb: FormBuilder,
		private authService: AuthService

	) {
		super(new ValidationErrorModel());
		// this.options = fb.group({
		// 	status: new FormControl(),
		// 	floatLabel: 'auto',
		// });
	}

	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('groupIds').setValue(this.criteriaFormGroup.get('groupIds').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('tags').setValue(this.criteriaFormGroup.get('tags').value);

		}

		this.formGroup.get('like').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => this.controlModified());
		this.formGroup.get('groupIds').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('status').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => this.controlModified());
		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('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('allVersions').valueChanges
		.pipe(takeUntil(this._destroyed))
		.subscribe(x => this.controlModified());
		this.formGroup.get('tags').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 = {}; }
		// this.formGroup.patchValue({'status': this.status !== undefined ? this.status : 'null'});
	}

	setCriteria(criteria: DatasetCriteria): void {
		this.formGroup.get('like').patchValue(criteria.like);
		this.formGroup.get('groupIds').patchValue(criteria.groupIds);
		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('allVersions').patchValue(criteria.allVersions);
		this.formGroup.get('tags').patchValue(criteria.tags);
		this.formGroup.get('grantStatus').patchValue(criteria.grantStatus);
		// this.criteria = criteria;
	}

	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));
		}
		// if (this.refreshCallback != null &&
		// 	(this.criteria.like == null || this.criteria.like.length === 0 || this.criteria.like.length > 2)
		// ) {
		// 	this.refreshCallback();
		// }
	}

	filterTags(value: string): Observable<ExternalSourceItemModel[]> {
		this.filteredTags = undefined;
		this.filteringTagsAsync = true;

		const requestItem: RequestItem<TagCriteria> = new RequestItem();
		const criteria: TagCriteria = new TagCriteria();
		criteria.like = value;
		requestItem.criteria = criteria;
		return this.externalSourcesService.searchDatasetTags(requestItem);
	}

	filterDatasetTemplate(query: string): Observable<any[]> {
		const fields: Array<string> = new Array<string>();
		fields.push('asc');
		const datasetTemplateRequestItem: DataTableRequest<DatasetProfileCriteria> = new DataTableRequest(0, null, { fields: fields });
		datasetTemplateRequestItem.criteria = new DatasetProfileCriteria();
		datasetTemplateRequestItem.criteria.like = query;
		if (this.isPublic) {
			return this.datasetService.getDatasetProfiles(datasetTemplateRequestItem);
		} else {
		return this.datasetService.getDatasetProfilesUsedPaged(datasetTemplateRequestItem).pipe(map(x => x.data));
		}
	}

	filterDmps(value: string): Observable<DataTableData<DmpListingModel>> {
		const fields: Array<string> = new Array<string>();
		fields.push('asc');

		// if (this.isPublic) {
		// 	const dmpDataTableRequest: DataTableRequest<ExploreDmpCriteriaModel> = new DataTableRequest(0, null, { fields: fields });
		// dmpDataTableRequest.criteria = new ExploreDmpCriteriaModel();
		// dmpDataTableRequest.criteria.like = value;
		// 	return this.dmpService.getPublicPaged(dmpDataTableRequest, "autocomplete");
		// } else {
			const dmpDataTableRequest: DataTableRequest<DmpCriteria> = new DataTableRequest(0, null, { fields: fields });
		dmpDataTableRequest.criteria = new DmpCriteria();
		dmpDataTableRequest.criteria.like = value;
		if (this.isPublic) {
			dmpDataTableRequest.criteria.isPublic = true;
			dmpDataTableRequest.criteria.onlyPublic = true;
		}
		return this.dmpService.getPaged(dmpDataTableRequest, "autocomplete");
		// }
	}

	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;
		if (this.isPublic) {
			return this.grantService.getPublicPaged(grantRequestItem).pipe(map(x => x.data));
		} else {
			return this.grantService.getPaged(grantRequestItem, "autocomplete").pipe(map(x => x.data));
		}
	}

	filterOrganisations(value: string) {
		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;
		if (this.isPublic) {
			return this.organisationService.searchPublicOrganisations(dataTableRequest).pipe(map(x => x.data));
		} else {
			return 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));
	}

	fileImport(event) {
		const dialogRef = this.dialog.open(DatasetUploadDialogue, {
			data: {
				fileList: FileList,
				success: Boolean,
				datasetTitle: String,
				dmpId: String,
				datasetProfileId: String,
				dmpSearchEnabled: this.dmpSearchEnabled,
				criteria: this.criteria
			}
		});
		dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
			if (result && result.success) {
				this.datasetWizardService.uploadXml(result.fileList, result.datasetTitle, result.dmpId, result.datasetProfileId)
					.pipe(takeUntil(this._destroyed))
					.subscribe(
						complete => this.onCallbackSuccess(),
						error => this.onCallbackError(error)
					);
			}
		})
	}

	onCallbackSuccess(): void {
		this.uiNotificationService.snackBarNotification(this.language.instant('DATASET-UPLOAD.SNACK-BAR.SUCCESSFUL-CREATION'), SnackBarNotificationLevel.Success);
		this.router.navigate(['/plans']);
	}

	onCallbackError(error: any) {
		this.uiNotificationService.snackBarNotification(this.language.instant('DATASET-UPLOAD.SNACK-BAR.UNSUCCESSFUL'), SnackBarNotificationLevel.Success);
	}

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