
import { Component, Inject, OnInit } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { DataTableData } from '@app/core/model/data-table/data-table-data';
import { DataTableRequest } from '@app/core/model/data-table/data-table-request';
import { DatasetProfileModel } from '@app/core/model/dataset/dataset-profile';
import { DmpModel } from '@app/core/model/dmp/dmp';
import { DmpListingModel } from '@app/core/model/dmp/dmp-listing';
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 { RequestItem } from '@app/core/query/request-item';
import { DatasetWizardService } from '@app/core/services/dataset-wizard/dataset-wizard.service';
import { DmpService } from '@app/core/services/dmp/dmp.service';
import { BaseCriteriaComponent } from '@app/ui/misc/criteria/base-criteria.component';
import { ValidationErrorModel } from '@common/forms/validation/error-model/validation-error-model';
import { Observable } from 'rxjs';
import { map, takeUntil } from 'rxjs/operators';

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

	public dialogueCriteria: any;
	datasetTitle: string;
	dmp: DmpModel;
	datasetProfile: DatasetProfileModel;
	availableProfiles: DatasetProfileModel[] = [];

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

	constructor(
		public dialogRef: MatDialogRef<DatasetUploadDialogue>,
		public dmpService: DmpService,
		private datasetWizardService: DatasetWizardService,
		@Inject(MAT_DIALOG_DATA) public data: any,
	) { super(new ValidationErrorModel()); }

	ngOnInit() {
		super.ngOnInit();
		if (this.dialogueCriteria == null) { this.dialogueCriteria = {}; }
		if (!this.data.dmpSearchEnabled) {
			this.dialogueCriteria = this.data.criteria;
			this.dmp = this.dialogueCriteria.dmpIds[0];
			this.loadDatasetProfiles();
		}
	}

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

	confirm() {
		this.data.success = true;
		this.data.datasetTitle = this.datasetTitle;
		this.data.dmpId = this.dmp.id;
		this.data.datasetProfileId = this.datasetProfile.id;
		this.dialogRef.close(this.data);
	}

	uploadFile(event) {
		const fileList: FileList = event.target.files
		this.data.fileList = fileList;
		if (this.data.fileList.length > 0) {
			this.datasetTitle = fileList.item(0).name;
		}
	}

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

	controlModified(): void {
		this.loadDatasetProfiles();
		if (!this.dmp) {
			this.availableProfiles = [];
		}
		this.clearErrorModel();
		if (this.refreshCallback != null &&
			(this.dialogueCriteria.like == null || this.dialogueCriteria.like.length === 0 || this.dialogueCriteria.like.length > 2)
		) {
			this.refreshCallback();
		}
	}

	loadDatasetProfiles() {
		const datasetProfileRequestItem: RequestItem<DatasetProfileCriteria> = new RequestItem();
		datasetProfileRequestItem.criteria = new DatasetProfileCriteria();
		if (this.dmp) {
			datasetProfileRequestItem.criteria.id = this.dmp.id;
		}
		if (datasetProfileRequestItem.criteria.id) {
			this.datasetWizardService.getAvailableProfiles(datasetProfileRequestItem)
				.pipe(takeUntil(this._destroyed))
				.subscribe(items => {
					this.availableProfiles = items;
					if (this.availableProfiles.length === 1) {
						this.datasetProfile = this.availableProfiles[0];
					}
				});
		}
	}

	setCriteriaDialogue(criteria: DatasetCriteria): void {
		this.dialogueCriteria = criteria;
	}

	disableButton() {
		if (!(this.data.fileList.length > 0) || !this.dmp) {
			return true;
		}
		else {
			return false;
		}
	}

	disableDatasetName() {
		if (!(this.data.fileList.length > 0)) {
			return true;
		}
		else {
			return false;
		}
	}

	disableDmpSearch() {
		if (!(this.data.fileList.length > 0) || !this.data.dmpSearchEnabled) {
			return true;
		}
		else {
			return false;
		}
	}

	disableDatasetProfile() {
		if (!this.dmp || (!this.data.dmpSearchEnabled && !(this.data.fileList.length > 0)) || (!this.data.dmpSearchEnabled && this.availableProfiles.length === 1)) {
			return true;
		}
		else {
			return false;
		}
	}
}
