import { Component, Inject } from '@angular/core';
import { MatDialog, 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, takeUntil } 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';
import { DatasetPreviewDialogComponent } from '../../dataset-preview/dataset-preview-dialog.component';
import { BaseComponent } from '@common/base/base.component';
import { MatomoService } from '@app/core/services/matomo/matomo-service';
import { HttpClient } from '@angular/common/http';

@Component({
	selector: 'dmp-upload-dialogue',
	templateUrl: './dmp-upload-dialogue.component.html',
	styleUrls: ['./dmp-upload-dialogue.component.scss']
})
export class DmpUploadDialogue extends BaseComponent {
	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'],
		popupItemActionIcon: 'visibility'
	};


	constructor(
		public dialogRef: MatDialogRef<DmpUploadDialogue>,
		private _service: DmpService,
		private dialog: MatDialog,
		private httpClient: HttpClient,
		private matomoService: MatomoService,
		@Inject(MAT_DIALOG_DATA) public data: any,
	) {
		super();
	}

	ngOnInit() {
		this.matomoService.trackPageView('DMP Upload Dialog');
	}

	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) {
		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;
	}

	onPreviewTemplate(event) {
		const dialogRef = this.dialog.open(DatasetPreviewDialogComponent, {
			width: '590px',
			minHeight: '200px',
			restoreFocus: false,
			data: {
				template: event
			},
			panelClass: 'custom-modalbox'
		});
		dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
			if (result) {
				if(!this.dmpProfiles) {
					this.dmpProfiles = [];
				}
				this.dmpProfiles.push(event);
				this.profilesAutoCompleteConfiguration = {
					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'],
					popupItemActionIcon: 'visibility'
				};
			}
		});
	}

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

	hasFile(): boolean {
		return this.files && this.files.length > 0;
	}
}
