
import { Component, Input, OnInit } 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';

@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;
	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()
	});

	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
	) {
		super(new ValidationErrorModel());
		// this.options = fb.group({
		// 	status: new FormControl(),
		// 	floatLabel: 'auto',
		// });
	}

	ngOnInit() {
		super.ngOnInit();
		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());
		// if (this.criteria == null) { this.criteria = {}; }
	}

	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.criteria = criteria;
	}

	controlModified(): void {
		this.clearErrorModel();
		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) {
		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;
		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');
		const dmpDataTableRequest: DataTableRequest<DmpCriteria> = new DataTableRequest(0, null, { fields: fields });
		dmpDataTableRequest.criteria = new DmpCriteria();
		dmpDataTableRequest.criteria.like = value;
		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;
		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;
		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);
	}
}
