import { Component, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialog } from '@angular/material/dialog';
import { BaseComponent } from '@common/base/base.component';
import { SingleAutoCompleteConfiguration } from '@app/library/auto-complete/single/single-auto-complete-configuration';
import { TranslateService } from '@ngx-translate/core';
import { Observable } from 'rxjs';
import { DmpListingModel } from '@app/core/model/dmp/dmp-listing';
import { DataTableRequest } from '@app/core/model/data-table/data-table-request';
import { DmpCriteria } from '@app/core/query/dmp/dmp-criteria';
import { DmpStatus } from '@app/core/common/enum/dmp-status';
import { map } from 'rxjs/operators';
import { DmpService } from '@app/core/services/dmp/dmp.service';
import { FormGroup } from '@angular/forms';

@Component({
	selector: 'app-start-new-dataset',
	templateUrl: './start-new-dataset-dialog.component.html',
	styleUrls: ['./start-new-dataset-dialog.component.scss']
})
export class StartNewDatasetDialogComponent extends BaseComponent {

	public isDialog: boolean = false;
	public formGroup: FormGroup;

	dmpAutoCompleteConfiguration: SingleAutoCompleteConfiguration = {
		filterFn: this.searchDmp.bind(this),
		initialItems: (extraData) => this.searchDmp(''),
		displayFn: (item) => this.getDatasetDisplay(item),
		titleFn: (item) => item['label'],
		subtitleFn: (item) => {try{return this.language.instant('DATASET-WIZARD.FIRST-STEP.SUB-TITLE') + new Date(item['creationTime']).toISOString();}catch{return '-';}}
	};

	constructor(
		public dialogRef: MatDialogRef<StartNewDatasetDialogComponent>,
		@Inject(MAT_DIALOG_DATA) public data: any,
		public dialog: MatDialog,
		private language: TranslateService,
		private dmpService: DmpService
	) {
		super();
		this.formGroup = data.formGroup;
	}

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

	send() {
		this.dialogRef.close(this.data);
	}

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

	next() {
		this.dialogRef.close(this.data);
	}

	startNewDmp() {
		this.data.startNewDmp = true;
		this.dialogRef.close(this.data);
	}

	searchDmp(query: string): Observable<DmpListingModel[]> {
		const fields: Array<string> = new Array<string>();
		fields.push('-created');
		const dmpDataTableRequest: DataTableRequest<DmpCriteria> = new DataTableRequest(0, null, { fields: fields });
		dmpDataTableRequest.criteria = new DmpCriteria();
		dmpDataTableRequest.criteria.like = query;
		dmpDataTableRequest.criteria.status = DmpStatus.Draft;
		return this.dmpService.getPaged(dmpDataTableRequest, "autocomplete").pipe(map(x => x.data));
	}

	getDatasetDisplay(item: any): string {
		// if (!this.isPublic) {
		// 	return (item['status'] ? this.language.instant('TYPES.DATASET-STATUS.FINALISED').toUpperCase() : this.language.instant('TYPES.DATASET-STATUS.DRAFT').toUpperCase()) + ': ' + item['label'];
		// }
		// else { return item['label']; }
		return item['label'] ? item['label'] : null;
	}
}
