import { Component, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { DmpService } from '../../../../core/services/dmp/dmp.service';
import { MultipleAutoCompleteConfiguration } from '@app/library/auto-complete/multiple/multiple-auto-complete-configuration';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { DatasetProfileModel } from '@app/core/model/dataset/dataset-profile';
import { DataTableRequest } from '@app/core/model/data-table/data-table-request';
import { DatasetProfileCriteria } from '@app/core/query/dataset-profile/dataset-profile-criteria';

@Component({
	selector: 'dmp-upload-dialogue',
	templateUrl: './dmp-upload-dialogue.component.html',
	styleUrls: ['./dmp-upload-dialogue.component.scss']
})
export class DmpUploadDialogue {
	dmpTitle: string;
	dmpProfiles: any[] = [];
	files: File[] = [];

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


	constructor(
		public dialogRef: MatDialogRef<DmpUploadDialogue>,
		private _service: DmpService,
		@Inject(MAT_DIALOG_DATA) public data: any,
	) { }

	cancel() {
		this.data.success = false;
		this.dialogRef.close(this.data);
	}

	close() {
		this.dialogRef.close(false);
	}

	confirm() {
		this.data.success = true;
		this.data.dmpTitle = this.dmpTitle;
		this.data.dmpProfiles = this.dmpProfiles;
		this.dialogRef.close(this.data);
	}

	uploadFile(event) {
		const fileList: FileList = event.target.files
		this.data.fileList = fileList;
		if (this.data.fileList.length > 0) {
			this.dmpTitle = fileList.item(0).name;
		}
		if (this.files.length === 1 ){
			this.files.splice(0, 1);
		}
		this.files.push(...event.target.files);
	}

	selectFile(event) {
		console.log(event)
		const fileList: FileList = event.addedFiles
		this.data.fileList = fileList;
		if (this.data.fileList.length > 0) {
			this.dmpTitle = fileList[0].name;
		}
		if (this.files.length === 1 ){
			this.files.splice(0, 1);
		}
		this.files.push(...event.addedFiles);
	}

	onRemove(event) {
		this.files.splice(0, 1);
		this.dmpTitle = null;
	}

	filterProfiles(value: string): Observable<DatasetProfileModel[]> {
		const request = new DataTableRequest<DatasetProfileCriteria>(null, null, { fields: ['+label'] });
		const criteria = new DatasetProfileCriteria();
		criteria.like = value;
		request.criteria = criteria;
		return this._service.searchDMPProfiles(request);
	}
}
