import { Component, Inject } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { DmpService } from '@app/core/services/dmp/dmp.service';
import { map, takeUntil } from 'rxjs/operators';
import { DmpModel } from '@app/core/model/dmp/dmp';
import { FormBuilder, FormArray, FormControl } from '@angular/forms';
import { DatasetDescriptionFormEditorModel } from '@app/ui/misc/dataset-description-form/dataset-description-form.model';
import { MultipleAutoCompleteConfiguration } from '@app/library/auto-complete/multiple/multiple-auto-complete-configuration';
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 { AvailableProfilesComponent } from '../../editor/available-profiles/available-profiles.component';
import { DatasetPreviewDialogComponent } from '../../dataset-preview/dataset-preview-dialog.component';
import { BaseComponent } from '@common/base/base.component';

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

	agreePrivacyPolicyNames = false;
	initialItems = [];
	profilesAutoCompleteConfiguration: MultipleAutoCompleteConfiguration;

	constructor(
		public dialogRef: MatDialogRef<CloneDialogComponent>,
		private dialog: MatDialog,
		private dmpService: DmpService,
		@Inject(MAT_DIALOG_DATA) public data: any
	) {
		super();

		this.selectionChanged(this.initialItems)

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

		if (this.data.isNewVersion) {
			// this.data.formGroup.get('label').disable();
		}
	}

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

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

	confirm() {
		this.dialogRef.close(true);
	}

	selectionChanged(selectedItems) {
		this.data.formGroup.removeControl('datasets');
		this.data.formGroup.addControl('datasets', new FormBuilder().array(new Array<FormControl>()));
		if (selectedItems && selectedItems.selectedOptions && selectedItems.selectedOptions.selected.length > 0) {
			selectedItems.selectedOptions.selected.forEach(element => {
				(<FormArray>this.data.formGroup.get('datasets')).push(new FormBuilder().group({ id: element.value }));
			});
		}
	}

	hasDatasets() {
		return this.data.datasets.length > 0;
	}

	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.dmpService.searchDMPProfiles(request);
	}

	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) {
				let profiles = this.data.formGroup.get('profiles').value;
				profiles.push(event);
				this.data.formGroup.get('profiles').setValue(profiles);
				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'
				};
			}
		});
	}

}
