import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ActivatedRoute, Router } from '@angular/router';
import { DatasetStatus } from '@app/core/common/enum/dataset-status';
import { DmpStatus } from '@app/core/common/enum/dmp-status';
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 { 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 { ExternalSourcesConfigurationService } from '@app/core/services/external-sources/external-sources-configuration.service';
import { ExternalSourcesService } from '@app/core/services/external-sources/external-sources.service';
import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service';
import { SingleAutoCompleteConfiguration } from '@app/library/auto-complete/single/single-auto-complete-configuration';
import { DatasetCopyDialogueComponent } from '@app/ui/dataset/dataset-wizard/dataset-copy-dialogue/dataset-copy-dialogue.component';
import { DatasetWizardEditorModel } from '@app/ui/dataset/dataset-wizard/dataset-wizard-editor.model';
import { BreadcrumbItem } from '@app/ui/misc/breadcrumb/definition/breadcrumb-item';
import { IBreadCrumbComponent } from '@app/ui/misc/breadcrumb/definition/IBreadCrumbComponent';
import { DatasetDescriptionFormEditorModel } from '@app/ui/misc/dataset-description-form/dataset-description-form.model';
import { LinkToScroll } from '@app/ui/misc/dataset-description-form/tableOfContentsMaterial/table-of-contents';
import { BaseComponent } from '@common/base/base.component';
import { FormService } from '@common/forms/form-service';
import { FormValidationErrorsDialogComponent } from '@common/forms/form-validation-errors-dialog/form-validation-errors-dialog.component';
import { ValidationErrorModel } from '@common/forms/validation/error-model/validation-error-model';
import { ConfirmationDialogComponent } from '@common/modules/confirmation-dialog/confirmation-dialog.component';
import { TranslateService } from '@ngx-translate/core';
import * as FileSaver from 'file-saver';
import { Observable, of as observableOf } from 'rxjs';
import { catchError, map, takeUntil } from 'rxjs/operators';

@Component({
	selector: 'app-dataset-wizard-component',
	templateUrl: 'dataset-wizard.component.html',
	styleUrls: ['./dataset-wizard.component.scss']
})
export class DatasetWizardComponent extends BaseComponent implements OnInit, IBreadCrumbComponent {

	breadCrumbs: Observable<BreadcrumbItem[]>;
	viewOnly = false;
	editMode = false;
	publicMode = false;

	DatasetStatus = DatasetStatus;
	dmpAutoCompleteConfiguration: SingleAutoCompleteConfiguration;

	datasetWizardModel: DatasetWizardEditorModel;
	isNew = true;
	isCopy = false;
	formGroup: FormGroup = null;
	datasetProfileDefinitionModel: DatasetDescriptionFormEditorModel;

	availableProfiles: DatasetProfileModel[] = [];
	itemId: string;
	publicId: string;
	profileUpdateId: string;
	downloadDocumentId: string;
	isLinear = false;

	constructor(
		private datasetWizardService: DatasetWizardService,
		private route: ActivatedRoute,
		public snackBar: MatSnackBar,
		public router: Router,
		public language: TranslateService,
		public externalSourcesService: ExternalSourcesService,
		public dmpService: DmpService,
		public dialog: MatDialog,
		public externalSourcesConfigurationService: ExternalSourcesConfigurationService,
		private uiNotificationService: UiNotificationService,
		private formService: FormService
	) {
		super();
	}

	ngOnInit() {
		this.route
			.data
			.pipe(takeUntil(this._destroyed))
			.subscribe(v => this.viewOnly = v['public']);

		const dmpRequestItem: RequestItem<DmpCriteria> = new RequestItem();
		dmpRequestItem.criteria = new DmpCriteria();

		this.dmpAutoCompleteConfiguration = {
			filterFn: this.searchDmp.bind(this),
			initialItems: (extraData) => this.searchDmp(''),
			displayFn: (item) => this.getDatasetDisplay(item),
			titleFn: (item) => item['label'],
			subtitleFn: (item) => this.language.instant('DATASET-WIZARD.FIRST-STEP.SUB-TITLE') + new Date(item['creationTime']).toISOString()
			// 	iconFn: (item) => this.publicMode ? '' : (item['status'] ? 'lock' : 'lock_open'),
			// 	linkFn: (item) => this.publicMode ? '/explore-plans/overview/' + item['id'] : '/plans/overview/' + item['id']
		};

		const params = this.route.snapshot.params;
		const queryParams = this.route.snapshot.queryParams;
		this.itemId = params['id'];
		const dmpId = params['dmpId'];
		const newDmpId = queryParams['newDmpId'];
		this.publicId = params['publicId'];
		this.profileUpdateId = params['updateId'];

		this.itemId ? this.downloadDocumentId = this.itemId : this.downloadDocumentId = this.publicId

		if (this.itemId != null && newDmpId == null) {
			this.isNew = false;
			this.datasetWizardService.getSingle(this.itemId)
				.pipe(takeUntil(this._destroyed))
				.subscribe(data => {
					this.datasetWizardModel = new DatasetWizardEditorModel().fromModel(data);
					this.needsUpdate();
					this.breadCrumbs = observableOf([
						{
							parentComponentName: null,
							label: this.datasetWizardModel.label,
							url: '/datasets/edit/' + this.datasetWizardModel.id,
							notFoundResolver: [
								{
									parentComponentName: null,
									label: this.language.instant('NAV-BAR.MY-DATASET-DESCRIPTIONS').toUpperCase(),
									url: '/datasets'
								},
							]
						}]);
					this.formGroup = this.datasetWizardModel.buildForm();
					this.editMode = this.datasetWizardModel.status === DatasetStatus.Draft;
					if (this.datasetWizardModel.status === DatasetStatus.Finalized) {
						this.formGroup.disable();
						this.viewOnly = true;
					}
					// if (this.viewOnly) { this.formGroup.disable(); } // For future use, to make Dataset edit like DMP.
					this.loadDatasetProfiles();
					this.registerFormListeners();
					// this.availableProfiles = this.datasetWizardModel.dmp.profiles;
				},
					error => {
						this.uiNotificationService.snackBarNotification(this.language.instant('DATASET-WIZARD.MESSAGES.DATASET-NOT-FOUND'), SnackBarNotificationLevel.Error);
						this.router.navigate(['/datasets/edit/' + this.itemId]);
						return observableOf(null);
					});
		} else if (dmpId != null) {
			this.isNew = true;
			this.dmpService.getSingle(dmpId).pipe(map(data => data as DmpModel))
				.pipe(takeUntil(this._destroyed))
				.subscribe(data => {
					this.datasetWizardModel = new DatasetWizardEditorModel();
					setTimeout(() => {
						this.datasetWizardModel.dmp = data;
						this.formGroup = this.datasetWizardModel.buildForm();
						this.editMode = this.datasetWizardModel.status === DatasetStatus.Draft;
						this.formGroup.get('dmp').disable();

						this.loadDatasetProfiles();
						this.registerFormListeners();
						// this.availableProfiles = data.profiles;

						this.breadCrumbs = observableOf([
							{
								parentComponentName: null,
								label: this.language.instant('NAV-BAR.MY-DATASET-DESCRIPTIONS'),
								url: '/datasets',
								notFoundResolver: [
									// {
									// 	parentComponentName: null,
									// 	label: this.datasetWizardModel.dmp.grant.label,
									// 	url: '/grants/edit/' + this.datasetWizardModel.dmp.grant.id
									// },
									{
										parentComponentName: null,
										label: this.datasetWizardModel.dmp.label,
										url: '/plans/edit/' + this.datasetWizardModel.dmp.id,
									}]
							}]);
					});
				});
		} else if (newDmpId != null) {
			this.isNew = false;
			this.isCopy = true;
			this.datasetWizardService.getSingle(this.itemId)
				.pipe(takeUntil(this._destroyed))
				.subscribe(data => {
					this.datasetWizardModel = new DatasetWizardEditorModel().fromModel(data);
					this.formGroup = this.datasetWizardModel.buildForm();
					this.formGroup.get('id').setValue(null);
					this.dmpService.getSingle(newDmpId).pipe(map(data => data as DmpModel))
						.pipe(takeUntil(this._destroyed))
						.subscribe(data => {
							setTimeout(() => {
								this.datasetWizardModel.dmp = data;
								this.formGroup.get('dmp').setValue(this.datasetWizardModel.dmp);

								this.loadDatasetProfiles();
								this.breadCrumbs = observableOf([
									{
										parentComponentName: null,
										label: this.language.instant('NAV-BAR.MY-DATASET-DESCRIPTIONS'),
										url: '/datasets',
										notFoundResolver: [
											// {
											// 	parentComponentName: null,
											// 	label: this.datasetWizardModel.dmp.grant.label,
											// 	url: '/grants/edit/' + this.datasetWizardModel.dmp.grant.id
											// },
											{
												parentComponentName: null,
												label: this.datasetWizardModel.dmp.label,
												url: '/plans/edit/' + this.datasetWizardModel.dmp.id,
											}
										]
									}]);
							});
						});
					this.editMode = this.datasetWizardModel.status === DatasetStatus.Draft;
					if (this.datasetWizardModel.status === DatasetStatus.Finalized) {
						this.formGroup.disable();
						this.viewOnly = true;
					}
					// if (this.viewOnly) { this.formGroup.disable(); } // For future use, to make Dataset edit like DMP.
					this.loadDatasetProfiles();
					// this.availableProfiles = data.dmp.profiles;
				});
		} else if (this.publicId != null) {  // For Finalized -> Public Datasets
			this.isNew = false;
			this.datasetWizardService.getSinglePublic(this.publicId)
				.pipe(takeUntil(this._destroyed)).pipe(
					catchError((error: any) => {
						this.uiNotificationService.snackBarNotification(error.error.message, SnackBarNotificationLevel.Error);
						this.router.navigate(['/datasets/publicEdit/' + this.publicId]);
						return observableOf(null);
					}))
				.subscribe(data => {
					if (data) {
						this.datasetWizardModel = new DatasetWizardEditorModel().fromModel(data);
						this.formGroup = this.datasetWizardModel.buildForm();
						this.editMode = this.datasetWizardModel.status === DatasetStatus.Draft;
						if (this.datasetWizardModel.status === DatasetStatus.Finalized) {
							this.formGroup.disable();
							this.viewOnly = true;
						}
						this.formGroup.get('dmp').setValue(this.datasetWizardModel.dmp);
						this.loadDatasetProfiles();
						const breadcrumbs = [];
						breadcrumbs.push({ parentComponentName: null, label: this.language.instant('NAV-BAR.PUBLIC DATASETS'), url: '/explore' });
						breadcrumbs.push({ parentComponentName: null, label: this.datasetWizardModel.label, url: '/datasets/publicEdit/' + this.datasetWizardModel.id });
						this.breadCrumbs = observableOf(breadcrumbs);
					}
				});
			this.publicMode = true;
		} else if (this.profileUpdateId != null) {
			this.datasetWizardService.updateDatasetProfile(this.profileUpdateId)
				.pipe(takeUntil(this._destroyed))
				.subscribe(data => {
					this.datasetWizardModel = new DatasetWizardEditorModel().fromModel(data);
					this.needsUpdate();
					this.breadCrumbs = observableOf([
						{
							parentComponentName: null,
							label: this.language.instant('NAV-BAR.MY-DATASET-DESCRIPTIONS'),
							url: '/datasets',
							notFoundResolver: [
								// {
								// 	parentComponentName: null,
								// 	label: this.datasetWizardModel.dmp.grant.label,
								// 	url: '/grants/edit/' + this.datasetWizardModel.dmp.grant.id
								// },
								{
									parentComponentName: null,
									label: this.datasetWizardModel.dmp.label,
									url: '/plans/edit/' + this.datasetWizardModel.dmp.id,
								},
							]
						}]);
					this.formGroup = this.datasetWizardModel.buildForm();
					this.editMode = this.datasetWizardModel.status === DatasetStatus.Draft;
					if (this.datasetWizardModel.status === DatasetStatus.Finalized) {
						this.formGroup.disable();
						this.viewOnly = true;
					}
					// if (this.viewOnly) { this.formGroup.disable(); } // For future use, to make Dataset edit like DMP.
					this.loadDatasetProfiles();
				});
		} else {
			this.datasetWizardModel = new DatasetWizardEditorModel();
			this.formGroup = this.datasetWizardModel.buildForm();
			this.editMode = this.datasetWizardModel.status === DatasetStatus.Draft;
			if (this.datasetWizardModel.status === DatasetStatus.Finalized) {
				this.formGroup.disable();
				this.viewOnly = true;
			}
			//if (this.viewOnly) { this.formGroup.disable(); } // For future use, to make Dataset edit like DMP.
			this.registerFormListeners();
			this.dmpValueChanged(null);
			this.breadCrumbs = observableOf([
				{
					parentComponentName: null,
					label: this.language.instant('DATASET-LISTING.ACTIONS.CREATE-NEW').toUpperCase(),
					url: '/datasets/new/'
				}]);
		}

		// this.route.params
		// 	.pipe(takeUntil(this._destroyed))
		// 	.subscribe((params: Params) => {
		// 		const itemId = params['id'];
		// 		if (itemId != null) { setTimeout(() => this.stepper.selectedIndex = 2); }
		// 	});
	}

	registerFormListeners() {
		this.formGroup.get('dmp').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => {
				this.dmpValueChanged(x);
			});
		this.formGroup.get('profile').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => {
				this.datasetProfileValueChanged(x);
			});
	}

	dmpValueChanged(dmp: DmpListingModel) {
		if (dmp) {
			this.formGroup.get('profile').enable();
			this.loadDatasetProfiles();
		}
		else {
			this.availableProfiles = [];
			this.formGroup.get('profile').reset();
			this.formGroup.get('profile').disable();
			this.formGroup.removeControl('datasetProfileDefinition');
		}
	}

	datasetProfileValueChanged(profiledId: string) {
		if (profiledId && profiledId.length > 0) {
			this.formGroup.removeControl('datasetProfileDefinition');
			this.getDefinition();
		}
	}

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

	loadDatasetProfiles() {
		const datasetProfileRequestItem: RequestItem<DatasetProfileCriteria> = new RequestItem();
		datasetProfileRequestItem.criteria = new DatasetProfileCriteria();
		datasetProfileRequestItem.criteria.id = this.formGroup.get('dmp').value.id;
		if (datasetProfileRequestItem.criteria.id) {
			this.datasetWizardService.getAvailableProfiles(datasetProfileRequestItem)
				.pipe(takeUntil(this._destroyed))
				.subscribe(items => {
					this.availableProfiles = items;
				});
		}
	}

	public cancel(): void {
		this.router.navigate(['/datasets']);
	}

	getDatasetDisplay(item: any): string {
		if (!this.publicMode) {
			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']; }
	}

	getDefinition() {
		// if (this.formGroup.invalid) { setTimeout(() => this.stepper.selectedIndex = 0); return; }
		this.datasetWizardService.getDefinition(this.formGroup.get('profile').value)
			.pipe(takeUntil(this._destroyed))
			.subscribe(item => {
				this.datasetWizardModel.datasetProfileDefinition = new DatasetDescriptionFormEditorModel().fromModel(item);
				this.datasetProfileDefinitionModel = this.datasetWizardModel.datasetProfileDefinition;
				this.formGroup.addControl('datasetProfileDefinition', this.datasetProfileDefinitionModel.buildForm());
			});
	}

	// formSubmit(): void {
	// 	if (!this.isFormValid()) { return; }
	// 	this.onSubmit();
	// }

	public isFormValid() {
		return this.formGroup.valid;
	}

	public isSemiFormValid(formGroup: FormGroup): boolean {
		var isValid: boolean = true;
		Object.keys(formGroup.controls).forEach(controlName => {
			if (controlName != 'datasetProfileDefinition' && !formGroup.get(controlName).disabled && !(formGroup.get(controlName).valid)) {
				isValid = false;
			}
		});
		return isValid;
	}

	// onSubmit(): void {
	// 	this.datasetWizardService.createDataset(this.formGroup.value)
	// 		.pipe(takeUntil(this._destroyed))
	// 		.subscribe(
	// 			complete => {
	// 				this.datasetWizardService.getSingle(complete.id)
	// 					.pipe(takeUntil(this._destroyed))
	// 					.subscribe(
	// 						result => {
	// 							this.datasetWizardModel = new DatasetWizardEditorModel().fromModel(result);
	// 						}
	// 					);
	// 				this.onCallbackSuccess();
	// 			},
	// 			error => this.onCallbackError(error)
	// 		);
	// }

	submit() {
		this.datasetWizardService.createDataset(this.formGroup.getRawValue())
			.pipe(takeUntil(this._destroyed))
			.subscribe(
				data => {
					this.onCallbackSuccess(this.datasetWizardModel.id);
				},
				error => this.onCallbackError(error));
	}

	save() {
		this.formService.touchAllFormFields(this.formGroup);
		if (!this.isSemiFormValid(this.formGroup)) {
			this.showValidationErrorsDialog();
			return;
		}
		this.submit();
	}

	private showValidationErrorsDialog(projectOnly?: boolean) {
		const dialogRef = this.dialog.open(FormValidationErrorsDialogComponent, {
			disableClose: true,
			data: {
				formGroup: this.formGroup,
				projectOnly: projectOnly
			},
		});
	}

	hasReversableStatus(): boolean {
		if (this.formGroup.get('dmp').value) {
			return (this.formGroup.get('dmp').value.status == DmpStatus.Draft && this.formGroup.get('status').value == DatasetStatus.Finalized);
		} else {
			return false;
		}
	}

	hasNotReversableStatus(): boolean {
		if (this.formGroup.get('dmp').value && !this.publicMode) {
			return (this.formGroup.get('dmp').value.status == DmpStatus.Finalized && this.formGroup.get('status').value == DatasetStatus.Finalized);
		} else {
			return false;
		}
	}

	reverse() {
		this.viewOnly = false;
		this.datasetWizardModel.status = DatasetStatus.Draft;
		setTimeout(x => { this.formGroup = null; });
		setTimeout(x => {
			this.formGroup = this.datasetWizardModel.buildForm();
			this.registerFormListeners();
		});

	}

	saveFinalize() {
		this.formService.touchAllFormFields(this.formGroup);
		if (!this.isFormValid()) {
			this.showValidationErrorsDialog();
			return;
		}
		const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
			restoreFocus: false,
			data: {
				message: this.language.instant('GENERAL.CONFIRMATION-DIALOG.FINALIZE-ITEM'),
				confirmButton: this.language.instant('QUICKWIZARD.SAVE-DIALOG.ACTIONS.AFFIRMATIVE'),
				cancelButton: this.language.instant('QUICKWIZARD.SAVE-DIALOG.ACTIONS.NEGATIVE'),
				isDeleteConfirmation: false
			}
		});
		dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
			if (result) {
				if (!this.isFormValid()) { return; }
				this.formGroup.get('status').setValue(DatasetStatus.Finalized);
				this.submit();
			}
		});
	}

	onCallbackSuccess(id?: String): void {
		this.uiNotificationService.snackBarNotification(this.isNew ? this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-CREATION') : this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-UPDATE'), SnackBarNotificationLevel.Success);
		id ? this.router.navigate(['/reload']).then(() => { this.router.navigate(['/datasets', 'edit', id]); }) : this.router.navigate(['/datasets']);
	}

	onCallbackError(error: any) {
		this.setErrorModel(error.error);
	}

	public setErrorModel(validationErrorModel: ValidationErrorModel) {
		Object.keys(validationErrorModel).forEach(item => {
			(<any>this.datasetWizardModel.validationErrorModel)[item] = (<any>validationErrorModel)[item];
		});
	}

	downloadPDF(): void {
		this.datasetWizardService.downloadPDF(this.downloadDocumentId)
			.pipe(takeUntil(this._destroyed))
			.subscribe(response => {
				const blob = new Blob([response.body], { type: 'application/pdf' });
				const filename = this.getFilenameFromContentDispositionHeader(response.headers.get('Content-Disposition'));

				FileSaver.saveAs(blob, filename);
			});
	}

	downloadDOCX(): void {
		this.datasetWizardService.downloadDOCX(this.downloadDocumentId)
			.pipe(takeUntil(this._destroyed))
			.subscribe(response => {
				const blob = new Blob([response.body], { type: 'application/msword' });
				const filename = this.getFilenameFromContentDispositionHeader(response.headers.get('Content-Disposition'));

				FileSaver.saveAs(blob, filename);
			});

	}

	downloadXML(): void {
		this.datasetWizardService.downloadXML(this.downloadDocumentId)
			.pipe(takeUntil(this._destroyed))
			.subscribe(response => {
				const blob = new Blob([response.body], { type: 'application/xml' });
				const filename = this.getFilenameFromContentDispositionHeader(response.headers.get('Content-Disposition'));

				FileSaver.saveAs(blob, filename);
			});
	}

	// advancedClicked() {
	// 	const dialogRef = this.dialog.open(ExportMethodDialogComponent, {
	// 		maxWidth: '500px',
	// 		data: {
	// 			message: "Download as:",
	// 			XMLButton: "XML",
	// 			documentButton: "Document",
	// 			pdfButton: "PDF"
	// 		}
	// 	});
	// 	dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
	// 		if (result == "pdf") {
	// 			this.downloadPDF();
	// 		} else if (result == "xml") {
	// 			this.downloadXML();
	// 		} else if (result == "doc") {
	// 			this.downloadDOCX();
	// 		}
	// 	});
	// }

	getFilenameFromContentDispositionHeader(header: string): string {
		const regex: RegExp = new RegExp(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/g);

		const matches = header.match(regex);
		let filename: string;
		for (let i = 0; i < matches.length; i++) {
			const match = matches[i];
			if (match.includes('filename="')) {
				filename = match.substring(10, match.length - 1);
				break;
			} else if (match.includes('filename=')) {
				filename = match.substring(9);
				break;
			}
		}
		return filename;
	}

	public redirectToGrant() {
		this.router.navigate(['grants/edit/' + this.datasetWizardModel.dmp.grant.id]);
	}

	public redirectToDmp() {
		this.router.navigate(['plans/edit/' + this.datasetWizardModel.dmp.id]);
	}

	public enableForm() {
		if (this.formGroup.get('status').value !== DatasetStatus.Finalized) {
			this.editMode = true;
			this.viewOnly = false;
			this.formGroup.enable();
		} else {
			this.datasetWizardService.unlock(this.formGroup.get('id').value)
				.pipe(takeUntil(this._destroyed))
				.subscribe(x => {
					this.editMode = true;
					this.viewOnly = false;
					this.datasetWizardModel.status = DatasetStatus.Draft;
					this.formGroup.get('status').patchValue(DatasetStatus.Draft);
					this.formGroup.enable();
				});
		}
	}

	public disableForm() {
		this.editMode = false;
		//this.viewOnly = true;
		this.formGroup.disable();
	}

	openConfirm(dmpLabel, id): void {
		const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
			maxWidth: '300px',
			restoreFocus: false,
			data: {
				message: this.language.instant('GENERAL.CONFIRMATION-DIALOG.DELETE-ITEM'),
				confirmButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.DELETE'),
				cancelButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CANCEL'),
				isDeleteConfirmation: true
			}
		});
		dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
			if (result) {
				this.datasetWizardService.delete(id)
					.pipe(takeUntil(this._destroyed))
					.subscribe(
						complete => this.onCallbackSuccess(),
						error => this.onCallbackError(error)
					);
			}
		});
	}

	openDmpSearchDialogue() {
		const formControl = new FormControl();
		const dialogRef = this.dialog.open(DatasetCopyDialogueComponent, {
			width: '500px',
			restoreFocus: false,
			data: {
				formControl: formControl,
				datasetId: this.formGroup.value.id,
				datasetProfileId: this.formGroup.value.profile,
				datasetProfileExist: false,
				confirmButton: this.language.instant('DATASET-WIZARD.DIALOGUE.COPY'),
				cancelButton: this.language.instant('DATASET-WIZARD.DIALOGUE.CANCEL')
			}
		});

		dialogRef.afterClosed().pipe(takeUntil(this._destroyed))
			.subscribe(result => {
				if (result && result.datasetProfileExist) {
					const newDmpId = result.formControl.value.id
					this.router.navigate(['/datasets/copy/' + result.datasetId], { queryParams: { newDmpId: newDmpId } });
				}
			});
	}

	needsUpdate() {
		if (this.datasetWizardModel.isProfileLatestVersion || (this.datasetWizardModel.status === DatasetStatus.Finalized)
			|| (this.datasetWizardModel.isProfileLatestVersion == undefined && this.datasetWizardModel.status == undefined)) {
			return false;
		}
		else {
			return true
		}
	}

	openUpdateDatasetProfileDialogue() {
		const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
			restoreFocus: false,
			data: {
				message: this.language.instant('DATASET-EDITOR.VERSION-DIALOG.QUESTION'),
				confirmButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CONFIRM'),
				cancelButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CANCEL'),
				isDeleteConfirmation: false
			}
		});
		dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
			if (result) {
				this.profileUpdateId = this.itemId;
				this.uiNotificationService.snackBarNotification(this.language.instant('DATASET-WIZARD.MESSAGES.SUCCESS-UPDATE-DATASET-PROFILE'), SnackBarNotificationLevel.Success);
				this.router.navigate(['/datasets/profileupdate/' + this.profileUpdateId]);
			}
		});
	}

	linkToScroll: LinkToScroll;
	onStepFound(linkToScroll: LinkToScroll) {
		this.linkToScroll = linkToScroll;
	}
}
