import {ChangeDetectorRef, Component, OnInit, ViewChild} from '@angular/core';
import {AbstractControl, FormArray, 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 {
	Link,
	LinkToScroll,
	TableOfContents
} from '@app/ui/misc/dataset-description-form/tableOfContentsMaterial/table-of-contents';
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 {interval, Observable, of as observableOf} from 'rxjs';
import {catchError, debounceTime, filter, map, takeUntil} from 'rxjs/operators';
import {LockService} from '@app/core/services/lock/lock.service';
import {Location} from '@angular/common';
import {LockModel} from '@app/core/model/lock/lock.model';
import {Guid} from '@common/types/guid';
import {isNullOrUndefined} from '@app/utilities/enhancers/utils';
import {AuthService} from '@app/core/services/auth/auth.service';
import {ConfigurationService} from '@app/core/services/configuration/configuration.service';
import {SaveType} from '@app/core/common/enum/save-type';
import {DatasetWizardModel} from '@app/core/model/dataset/dataset-wizard';
import {MatomoService} from '@app/core/services/matomo/matomo-service';
import {HttpClient} from '@angular/common/http';
import {VisibilityRulesService} from '@app/ui/misc/dataset-description-form/visibility-rules/visibility-rules.service';
import {PopupNotificationDialogComponent} from '@app/library/notification/popup/popup-notification.component';
import {CheckDeactivateBaseComponent} from '@app/library/deactivate/deactivate.component';
import {PrefillDatasetComponent} from "@app/ui/dataset/dataset-wizard/prefill-dataset/prefill-dataset.component";
import {ToCEntry, ToCEntryType} from "@app/ui/misc/dataset-description-form/dataset-description.component";
import {dispatchFakeEvent} from "@angular/cdk/testing/testbed/fake-events";

@Component({
	selector: 'app-dataset-wizard-component',
	templateUrl: 'dataset-wizard.component.html',
	styleUrls: ['./dataset-wizard.component.scss']
})
export class DatasetWizardComponent extends CheckDeactivateBaseComponent implements OnInit, IBreadCrumbComponent {
	canDeactivate(): boolean {
		return !this.isDirty();
	}

	breadCrumbs: Observable<BreadcrumbItem[]>;
	viewOnly = false;
	editMode = false;
	publicMode = false;
	hasChanges = false;
	isDiscarded = false;
	formGroupRawValue: any;
	saving = 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;
	lock: LockModel;
	lockStatus: Boolean;

	step: number = 0;
	stepOffset: number = 1;

	saveAnd = SaveType;
	datasetSavedLinks: any = null;

	scrollTop: number;
	tocScrollTop: number;
	links: Link[] = [];
	//the table seraches for elements to scroll on page with id (TOCENTRY_ID_PREFIX+fieldsetId<Tocentry>)
	TOCENTRY_ID_PREFIX = "TocEntRy";
	showtocentriesErrors = false;
	@ViewChild('table0fContents') table0fContents: TableOfContents;
	hintErrors: boolean = false;
	datasetIsOnceSaved = false;

	fieldsetIdWithFocus: string;
	visRulesService: VisibilityRulesService;

	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,
		private lockService: LockService,
		private location: Location,
		private authService: AuthService,
		private configurationService: ConfigurationService,
		private httpClient: HttpClient,
		private matomoService: MatomoService
	) {
		super();
	}

	ngOnInit() {
		this.matomoService.trackPageView('Dataset Editor');
		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.lockService.checkLockStatus(data.id).pipe(takeUntil(this._destroyed)).subscribe(lockStatus => {
							this.lockStatus = lockStatus;
							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.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
							this.editMode = this.datasetWizardModel.status === DatasetStatus.Draft;
							if (this.datasetWizardModel.status === DatasetStatus.Finalized || lockStatus) {
								this.formGroup.disable();
								this.viewOnly = true;
							}
							if (!lockStatus && !isNullOrUndefined(this.authService.current())) {
								this.lock = new LockModel(data.id, this.authService.current());

								this.lockService.createOrUpdate(this.lock).pipe(takeUntil(this._destroyed)).subscribe(async result => {
									this.lock.id = Guid.parse(result);
									interval(this.configurationService.lockInterval).pipe(takeUntil(this._destroyed)).subscribe(() => this.pumpLock());
								});
							}
							// if (this.viewOnly) { this.formGroup.disable(); } // For future use, to make Dataset edit like DMP.
							this.loadDatasetProfiles();
							this.registerFormListeners();

							if (lockStatus) {
								this.dialog.open(PopupNotificationDialogComponent, {
									data: {
										title: this.language.instant('DATASET-WIZARD.LOCKED.TITLE'),
										message: this.language.instant('DATASET-WIZARD.LOCKED.MESSAGE')
									}, maxWidth: '30em'
								});
							}
							// this.availableProfiles = this.datasetWizardModel.dmp.profiles;
						})
					},
					error => {
						switch (error.status) {
							case 403:
								this.uiNotificationService.snackBarNotification(this.language.instant('DATASET-WIZARD.MESSAGES.DATASET-NOT-ALLOWED'), SnackBarNotificationLevel.Error);
								break;
							case 404:
								this.uiNotificationService.snackBarNotification(this.language.instant('DATASET-WIZARD.MESSAGES.DATASET-NOT-FOUND'), SnackBarNotificationLevel.Error);
								break;
							default:
								this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.ERRORS.HTTP-REQUEST-ERROR'), SnackBarNotificationLevel.Error);
						}
						this.router.navigate(['/datasets/']);
						return observableOf(null);
					});
		} else if (dmpId != null) {
			this.isNew = true;
			this.dmpService.getSingleNoDatasets(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.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
						this.editMode = this.datasetWizardModel.status === DatasetStatus.Draft;
						this.formGroup.get('dmp').disable();
						const dialogRef = this.dialog.open(PrefillDatasetComponent, {
							width: '590px',
							minHeight: '200px',
							restoreFocus: false,
							data: {
								availableProfiles: this.formGroup.get('dmp').value.profiles,
							},
							panelClass: 'custom-modalbox'
						});
						dialogRef.afterClosed().subscribe(result => {
							if(result) {
								this.datasetWizardModel = this.datasetWizardModel.fromModel(result);
								this.datasetWizardModel.dmp = data;
								this.formGroup = this.datasetWizardModel.buildForm();
								this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
								this.formGroup.get('dmp').disable();
								this.loadDatasetProfiles();
								this.registerFormListeners();
							}
						})
						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.lockService.checkLockStatus(data.id).pipe(takeUntil(this._destroyed)).subscribe(lockStatus => {
						this.lockStatus = lockStatus;
						this.datasetWizardModel = new DatasetWizardEditorModel().fromModel(data);
						this.datasetWizardModel.status = 0;
						this.formGroup = this.datasetWizardModel.buildForm();
						this.formGroup.get('id').setValue(null);
						this.dmpService.getSingleNoDatasets(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.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));

									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 || lockStatus) {
							this.formGroup.disable();
							this.viewOnly = true;
						}
						if (!lockStatus && !isNullOrUndefined(this.authService.current())) {
							this.lock = new LockModel(data.id, this.authService.current());

							this.lockService.createOrUpdate(this.lock).pipe(takeUntil(this._destroyed)).subscribe(async result => {
								this.lock.id = Guid.parse(result);
								interval(this.configurationService.lockInterval).pipe(takeUntil(this._destroyed)).subscribe(() => this.pumpLock());
							});
						}
						// 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.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
						this.formGroup.disable();
						this.viewOnly = true;
						this.editMode = this.datasetWizardModel.status === DatasetStatus.Draft;
						this.formGroup.get('dmp').setValue(this.datasetWizardModel.dmp);
						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.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));

					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.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));

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

	// private _listenersSubscription:Subscription = new Subscription();
	registerFormListeners() {
		// const dmpSubscription =
		this.formGroup.get('dmp').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => {
				this.dmpValueChanged(x);
			});
		// const profileSubscription =
		this.formGroup.get('profile').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => {
				if (x) {
					this.showtocentriesErrors = false;
					this.datasetProfileValueChanged(x.id);
					this.formChanged();
				}
			});
		// const labelSubscription =
		this.formGroup.get('label').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => {
				this.formChanged();
			});
		// const descriptionSubscription =
		this.formGroup.get('description').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => {
				this.formChanged();
			});
		// const uriSubscription =
		this.formGroup.get('uri').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => {
				this.formChanged();
			});
		// const tagsSubscription =
		this.formGroup.get('tags').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x => {
				this.formChanged();
			});
		if (this.formGroup.get('datasetProfileDefinition')) {
			// const datasetProfileDefinitionSubscription =
			this.formGroup.get('datasetProfileDefinition').valueChanges
				.pipe(takeUntil(this._destroyed))
				.subscribe(x => {
					this.formChanged();
				});
			// this._listenersSubscription.add(datasetProfileDefinitionSubscription);
		}

		// this._listenersSubscription.add(dmpSubscription);
		// this._listenersSubscription.add(profileSubscription);
		// this._listenersSubscription.add(labelSubscription);
		// this._listenersSubscription.add(descriptionSubscription);
		// this._listenersSubscription.add(uriSubscription);
		// this._listenersSubscription.add(tagsSubscription);
	}

	// private _unregisterFormListeners(){
	// 	this._listenersSubscription.unsubscribe();
	// 	this._listenersSubscription = new Subscription();
	// }

	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(profiledId);
			console.log(this.table0fContents.tocentries.length + 1);
		}
	}

	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 formChanged() {
		if (!this.isDiscarded) {
			this.hasChanges = true;
		}
	}

	public cancel(): void {
		if (!isNullOrUndefined(this.lock)) {
			this.lockService.unlockTarget(this.datasetWizardModel.id).pipe(takeUntil(this._destroyed)).subscribe(
				complete => {
					this.publicMode ? this.router.navigate(['/explore']) : this.router.navigate(['/datasets']);
				},
				error => {
					this.formGroup.get('status').setValue(DmpStatus.Draft);
					this.onCallbackError(error);
				}
			)
		} else {
			this.publicMode ? this.router.navigate(['/explore']) : 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(profileId: string) {
		// if (this.formGroup.invalid) { setTimeout(() => this.stepper.selectedIndex = 0); return; }
		this.datasetWizardService.getDefinition(profileId)
			.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());

				// const datasetProfileDefinitionForm = this.datasetProfileDefinitionModel.buildForm();

				// let profId = null;
				// try{
				// 	profId = this.formGroup.get('profile').value.id;
				// }catch{

				// }
				// if(this.formGroupRawValue && this.formGroupRawValue.datasetProfileDefinition && (this.formGroupRawValue.profile.id === profId)){
				// 	// this.formGroup.get('datasetProfileDefinition').patchValue( this.formGroupRawValue.datasetProfileDefinition);
				// 	datasetProfileDefinitionForm.patchValue(this.formGroupRawValue.datasetProfileDefinition);
				// }

				// this.formGroup.addControl('datasetProfileDefinition', datasetProfileDefinitionForm);
				this.formGroup.get('datasetProfileDefinition').valueChanges
					.pipe(debounceTime(600))
					.pipe(takeUntil(this._destroyed))
					.subscribe(x => {
						this.formChanged();
					});
			});
	}

	// 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(saveType?: SaveType) {
		this.scrollTop = document.getElementById('dataset-editor-form').scrollTop;
		this.tocScrollTop = document.getElementById('stepper-options').scrollTop;
		this.datasetWizardService.createDataset(this.formGroup.getRawValue())
			.pipe(takeUntil(this._destroyed))
			.subscribe(
				data => {
					this.hasChanges = false;
					this.datasetIsOnceSaved = true;
					this.onCallbackSuccess(data, saveType);
				},
				error => this.onCallbackError(error));
	}


	private _getErrorMessage(formControl: AbstractControl, name: string): string[] {
		const errors: string[] = [];
		Object.keys(formControl.errors).forEach(key => {
			if (key === 'required') {
				errors.push(this.language.instant(name + ": " + this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.REQUIRED')));
			}
			// if (key === 'required') { errors.push(this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.THIS-FIELD') + ' "' + this.getPlaceHolder(formControl) + '" ' + this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.HAS-ERROR') + ', ' + this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.REQUIRED')); }
			else if (key === 'email') {
				errors.push(this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.THIS-FIELD') + ' "' + name + '" ' + this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.HAS-ERROR') + ', ' + this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.EMAIL'));
			} else if (key === 'min') {
				errors.push(this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.THIS-FIELD') + ' "' + name + '" ' + this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.HAS-ERROR') + ', ' + this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.MIN-VALUE', {'min': formControl.getError('min').min}));
			} else if (key === 'max') {
				errors.push(this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.THIS-FIELD') + ' "' + name + '" ' + this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.HAS-ERROR') + ', ' + this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.MAX-VALUE', {'max': formControl.getError('max').max}));
			} else {
				errors.push(this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.THIS-FIELD') + ' "' + name + '" ' + this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.HAS-ERROR') + ', ' + formControl.errors[key].message);
			}
		});
		return errors;
	}

	private _getPlaceHolder(formControl: any): string {
		if (formControl.nativeElement.localName === 'input' || formControl.nativeElement.localName === 'textarea'
			|| formControl.nativeElement.localName === 'richTextarea') {
			return formControl.nativeElement.getAttribute('placeholder');
		} else if (formControl.nativeElement.localName === 'mat-select') {
			return formControl.nativeElement.getAttribute('placeholder');
		} else if (formControl.nativeElement.localName === 'app-single-auto-complete') {
			return (Array.from(formControl.nativeElement.firstChild.children).filter((x: any) => x.localName === 'input')[0] as any).getAttribute('placeholder');
		} else if (formControl.nativeElement.localName === 'app-multiple-auto-complete') {
			return (Array.from(formControl.nativeElement.firstChild.firstChild.firstChild.children).filter((x: any) => x.localName === 'input')[0] as any).getAttribute('placeholder');
		}
	}


	private _buildSemiFormErrorMessages(): string[] {//not including datasetProfileDefinition
		const errmess: string[] = [];
		Object.keys(this.formGroup.controls).forEach(controlName => {
			if (controlName != 'datasetProfileDefinition' && this.formGroup.get(controlName).invalid) {
				errmess.push(...this._buildErrorMessagesForAbstractControl(this.formGroup.get(controlName), controlName));
			}
		})

		return errmess;
	}

	// takes as an input an abstract control and gets its error messages[]
	private _buildErrorMessagesForAbstractControl(aControl: AbstractControl, controlName: string): string[] {
		const errmess: string[] = [];

		if (aControl.invalid) {

			if (aControl.errors) {
				//check if has placeholder
				if ((<any>aControl).nativeElement !== undefined && (<any>aControl).nativeElement !== null) {
					const placeholder = this._getPlaceHolder(aControl);
					if (placeholder) {
						controlName = placeholder;
					}
				}
				const errorMessage = this._getErrorMessage(aControl, controlName);

				errmess.push(...errorMessage);
			}

			/*in case the aControl is FormControl then the it should have provided its error messages above.
			No need to check case of FormControl below*/

			if (aControl instanceof FormGroup) {

				const fg = aControl as FormGroup;
				//check children
				Object.keys(fg.controls).forEach(controlName => {
					errmess.push(...this._buildErrorMessagesForAbstractControl(fg.get(controlName), controlName));
				});
			} else if (aControl instanceof FormArray) {

				const fa = aControl as FormArray;

				fa.controls.forEach((control, index) => {
					errmess.push(...this._buildErrorMessagesForAbstractControl(control, `${controlName} --> ${index + 1}`));
				});

			}
		}

		return errmess;
	}

	save(saveType?: SaveType) {
		this.saving = true;
		Object.keys(this.formGroup.controls).forEach(controlName => {
			if (controlName == 'datasetProfileDefinition') {
				return;
			}
			this.formService.touchAllFormFields(this.formGroup.get(controlName));
		})


		// this.formService.touchAllFormFields(this.formGroup);
		if (!this.isSemiFormValid(this.formGroup)) {
			//build messages
			const errorMessages = this._buildSemiFormErrorMessages();
			this.showValidationErrorsDialog(undefined, errorMessages);
			this.hintErrors = true;
			this.saving = false;
			return;
		}
		this.submit(saveType);
	}

	private showValidationErrorsDialog(projectOnly?: boolean, errmess?: string[]) {
		if (errmess) {
			const dialogRef = this.dialog.open(FormValidationErrorsDialogComponent, {
				disableClose: true,
				autoFocus: false,
				restoreFocus: false,
				data: {
					errorMessages: errmess,
					projectOnly: projectOnly
				},
			});
		} else {

			const dialogRef = this.dialog.open(FormValidationErrorsDialogComponent, {
				disableClose: true,
				autoFocus: false,
				restoreFocus: false,
				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.dialog.open(ConfirmationDialogComponent, {
			data: {
				message: this.language.instant('DATASET-WIZARD.ACTIONS.UNDO-FINALIZATION-QUESTION'),
				confirmButton: this.language.instant('DATASET-WIZARD.ACTIONS.CONFIRM'),
				cancelButton: this.language.instant('DATASET-WIZARD.ACTIONS.REJECT'),
			},
			maxWidth: '30em'
		})
			.afterClosed()
			.pipe(
				filter(x => x),
				takeUntil(this._destroyed)
			).subscribe(_ => {
			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);
		this.saving = true;
		if (!this.isSemiFormValid(this.formGroup) || (this.table0fContents && this.table0fContents.hasVisibleInvalidFields())) {
			// this.showValidationErrorsDialog();
			this.dialog.open(FormValidationErrorsDialogComponent, {
				data: {
					errorMessages: [this.language.instant('DATASET-WIZARD.MESSAGES.MISSING-FIELDS')]
				}
			})


			this.touchForm();
			this.hintErrors = true;
			this.saving = false;
			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(SaveType.finalize);
			}
		});
	}

	onCallbackSuccess(data?: DatasetWizardModel, saveType?: SaveType): void {
		this.uiNotificationService.snackBarNotification(this.isNew ? this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-CREATION') : this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-UPDATE'), SnackBarNotificationLevel.Success);
		if (data) {
			if (saveType === this.saveAnd.addNew) {
				this.router.navigate(['/reload']).then(() => {
					this.router.navigate(['/datasets', 'new', this.formGroup.get('dmp').value.id]);
				})
			} else if (saveType === this.saveAnd.close) {
				this.router.navigate(['/reload']).then(() => {
					this.router.navigate(['/plans', 'edit', this.formGroup.get('dmp').value.id]);
				});
			} else if (saveType === SaveType.finalize) {
				this.router.navigate(['/reload']).then(() => {
					this.router.navigate(['/datasets', 'edit', data.id]);
				});
			} else {
				this.datasetWizardModel = new DatasetWizardEditorModel().fromModel(data);
				this.editMode = this.datasetWizardModel.status === DatasetStatus.Draft;
				// setTimeout(() => { this.formGroup = null; });
				setTimeout(() => {
					this.formGroup.get('id').patchValue(data.id);
					this.formGroup.get('modified').patchValue(data.modified);
					this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
					this.hasChanges = false;

					// this.formGroup = this.datasetWizardModel.buildForm();
					// if (this.formGroup.get('datasetProfileDefinition')) {
					// 	this.formGroup.removeControl('datasetProfileDefinition');
					// 	this.getDefinition(data.profile.id);
					// 	this.maxStep = 1;
					// } else {
					// 	this.getDefinition(data.profile.id);
					// 	this.maxStep = 1;
					// }
				});

				setTimeout(() => {
					document.getElementById('dataset-editor-form').scrollTop = this.scrollTop;
					document.getElementById('stepper-options').scrollTop = this.tocScrollTop;
				}, 500);

				this.saving = false;
				this.isNew = false;
				// this.router.navigate(['/reload']).then(() => { this.router.navigate(['/datasets', 'edit', data.id]); });
			}
		} else {
			this.router.navigate(['/datasets']);
		}
	}

	onCallbackError(error: any) {
		const errmes = error && error.message ? error.message as string : null;
		let feedbackMessage = this.language.instant('DATASET-EDITOR.ERRORS.ERROR-OCCURED');
		if (errmes) {
			feedbackMessage += errmes;
		}
		this.uiNotificationService.snackBarNotification(feedbackMessage, SnackBarNotificationLevel.Warning);
		this.setErrorModel(error.error);
		this.saving = false;
	}

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

	private pumpLock() {
		this.lock.touchedAt = new Date();
		this.lockService.createOrUpdate(this.lock).pipe(takeUntil(this._destroyed)).subscribe(async result => {
			if (!isNullOrUndefined(result)) {
				this.lock.id = Guid.parse(result);
			} else {
				this.location.back();
			}
		});
	}

	getEntryVisibleFieldSets(entry: ToCEntry): ToCEntry[] {
		let fieldSets = [];
		if(entry.type === ToCEntryType.FieldSet && !this.table0fContents.internalTable.hiddenEntries.find(hiddenEntry => hiddenEntry === entry.id)) {
			fieldSets.push(entry);
		} else if(entry.type !== ToCEntryType.FieldSet) {
			entry.subEntries.forEach(subEntry => {
				fieldSets = fieldSets.concat(this.getEntryVisibleFieldSets(subEntry));
			});
		}
		return fieldSets;
	}

	get visibleFieldSets(): ToCEntry[]{
		let fieldSets = [];
		let arrays= this.table0fContents?this.table0fContents.tocentries.
		filter(entry => !this.table0fContents.internalTable.hiddenEntries.find(hiddenEntry => hiddenEntry === entry.id)).map(entry => {
			return this.getEntryVisibleFieldSets(entry);
			})
		:[];
		arrays.forEach(array => {
			fieldSets = fieldSets.concat(array);
		});
		return fieldSets;
	}

	getFirstFieldSet(entry: ToCEntry): ToCEntry {
		if(entry.type === ToCEntryType.FieldSet && !this.table0fContents.internalTable.hiddenEntries.find(hiddenEntry => hiddenEntry === entry.id)) {
			return entry;
		} else {
			let subEntries = entry.subEntries.filter(subEntry => !this.table0fContents.internalTable.hiddenEntries.find(hiddenEntry => hiddenEntry === subEntry.id));
			if(subEntries.length > 0) {
				return this.getFirstFieldSet(subEntries[0]);
			} else {
				return null;
			}
		}
	}

	public changeStep(selected: ToCEntry = null, execute: boolean = true) {
		if(execute) {
			if(selected) {
				let fieldSet = this.getFirstFieldSet(selected);
				let index = this.visibleFieldSets.findIndex(entry => entry.id === fieldSet.id);
				this.step = index + (selected.type === ToCEntryType.FieldSet?1:0.5);
			} else {
				this.step = 0;
			}
		}
	}

	get maxStep() {
		return this.visibleFieldSets.length;
	}

	public nextStep() {
		if (this.step < this.maxStep) {//view is changing
			this.step = Math.floor(this.step + 1);
			let entry = this.visibleFieldSets[this.step - 1];
			this.table0fContents.onToCentrySelected(entry, false);
			this.scroll(entry);
		}
	}

	public previousStep() {
		if (this.step > 0) {
			this.step = Math.ceil(this.step - 1);
			if(this.step >= 1) {
				let entry = this.visibleFieldSets[this.step - 1];
				this.table0fContents.onToCentrySelected(entry, false);
				this.scroll(entry);
			} else {
				this.table0fContents.onToCentrySelected(null, false);
				this.resetScroll();
			}
		}
	}

	private resetScroll() {
		document.getElementById('dataset-editor-form').scrollTop = 0;
	}

	private scroll(entry: ToCEntry) {
		document.getElementById(entry.id).scrollIntoView();
	}

	isDirty() {
		return this.formGroup.dirty && this.hasChanges; // do we need this.formGroup.dirty
	}

	discardChanges() {
		// this.isDiscarded = true;
		// this.hasChanges = false;
		// this.hintErrors = false;
		let messageText = "";
		let confirmButtonText = "";
		let cancelButtonText = "";
		let isDeleteConfirmation = false;

		if (this.isNew && !this.datasetIsOnceSaved) {

			messageText = this.language.instant('DATASET-EDITOR.ACTIONS.DISCARD.DISCARD-NEW-MESSAGE');
			confirmButtonText = this.language.instant('DATASET-EDITOR.ACTIONS.DISCARD.DISCARD-NEW-CONFIRM');
			cancelButtonText = this.language.instant('DATASET-EDITOR.ACTIONS.DISCARD.DISCARD-NEW-DENY');
			isDeleteConfirmation = true;

			// Object.keys(this.formGroup['controls']).forEach((key: string) => {
			// 	if (key !== 'dmp' && (key!== 'profile')) {
			// 		if(key === 'datasetProfileDefinition'){
			// 			this.formGroup.get(key).patchValue(this.datasetProfileDefinitionModel.buildForm().getRawValue);
			// 		}else{
			// 			this.formGroup.get(key).reset();
			// 		}

			// 	}
			// });
		} else {

			messageText = this.language.instant('DATASET-EDITOR.ACTIONS.DISCARD.DISCARD-EDITED-MESSAGE');
			confirmButtonText = this.language.instant('DATASET-EDITOR.ACTIONS.DISCARD.DISCARD-EDITED-CONFIRM');
			cancelButtonText = this.language.instant('DATASET-EDITOR.ACTIONS.DISCARD.DISCARD-EDITED-DENY');
			isDeleteConfirmation = false;

			// this.isDiscarded = true;
			// this.hasChanges = false;
			// this.hintErrors = false;
			// // this._unregisterFormListeners();
			// this.formGroup.patchValue(JSON.parse(JSON.stringify(this.formGroupRawValue)));
			// // this.registerFormListeners();
			// this.isDiscarded = false;


		}


		const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
			restoreFocus: false,
			data: {
				message: messageText,
				confirmButton: confirmButtonText,
				cancelButton: cancelButtonText,
				isDeleteConfirmation: true
			},
			maxWidth: '40em'
		});
		dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
			if (result) {
				this.backToDmp(this.formGroup.get('dmp').value.id)
			}
		});


		// this.isDiscarded = false;
	}

	addDataset(dmpId: string) {
		this.router.navigate(['/datasets', 'new', dmpId]);
	}

	backToDmp(id: string) {
		this.router.navigate(['/plans', 'edit', id]);
	}

	datasetInfoValid(): boolean {
		return this.formGroup.get('label') && this.formGroup.get('label').valid && this.formGroup.get('profile') && this.formGroup.get('profile').valid;
	}

	getLinks(currentLinks: Link[]) {
		this.links = currentLinks;
	}

	printForm() {
		console.log(this.formGroup);
	}

	printFormValue() {
		console.log(this.formGroup.value);
	}

	touchForm() {
		this.formGroup.markAllAsTouched();
		this.showtocentriesErrors = true;
	}

	// tocentries;
	// this.tocentries = this.getTocEntries(this.formGroup.get('datasetProfileDefinition')); //TODO


	// get tocentries(){
	// 	const form =  this.formGroup.get('datasetProfileDefinition')
	// 	if(!form) return null;

	// 	return this.getTocEntries(this.formGroup.get('datasetProfileDefinition'));
	// }


	// private _buildRecursively(form: FormGroup,whatAmI:ToCEntryType):ToCEntry{
	// 	if(!form) return null;

	// 	switch(whatAmI){
	// 		case ToCEntryType.Section:
	// 			const sections = form.get('sections') as FormArray;
	// 			const fieldsets = form.get('compositeFields') as FormArray;


	// 			const tempResult:ToCEntry[] = [];

	// 			if(sections &&sections.length){
	// 				sections.controls.forEach(section=>{
	// 					tempResult.push(this._buildRecursively(section as FormGroup, ToCEntryType.Section));
	// 				});

	// 			}else if(fieldsets && fieldsets.length){
	// 				fieldsets.controls.forEach(fieldset=>{
	// 					tempResult.push(this._buildRecursively(fieldset as FormGroup, ToCEntryType.FieldSet));
	// 				});
	// 			}
	// 			return {
	// 				form: form,
	// 				id: form.get('id').value,
	// 				label: form.get('title').value,
	// 				numbering: '',
	// 				subEntries:tempResult,
	// 				subEntriesType: sections &&sections.length? ToCEntryType.Section: ToCEntryType.FieldSet,
	// 				type: ToCEntryType.Section,
	// 				ordinal: form.get('ordinal').value
	// 			}
	// 		case ToCEntryType.FieldSet:
	// 			return {
	// 				form: form,
	// 				label:form.get('title').value,
	// 				id: form.get('id').value,
	// 				numbering:'s',
	// 				subEntries:[],
	// 				subEntriesType: ToCEntryType.Field,
	// 				type: ToCEntryType.FieldSet,
	// 				ordinal: form.get('ordinal').value
	// 			}
	// 	}
	// }

	// private _sortByOrdinal(tocentries: ToCEntry[]){

	// 	if(!tocentries || !tocentries.length) return;

	// 	tocentries.sort(this._customCompare);
	// 	tocentries.forEach(entry=>{
	// 		this._sortByOrdinal(entry.subEntries);
	// 	});
	// }

	// private _customCompare(a,b){
	// 	return a.ordinal - b.ordinal;
	// }

	// private _calculateNumbering(tocentries: ToCEntry[], depth:number[] = []){
	// 	if(!tocentries || !tocentries.length){
	// 		return;
	// 	}

	// 	let  prefixNumbering = depth.length? depth.join('.'): '';

	// 	if(depth.length) prefixNumbering = prefixNumbering+".";
	// 	tocentries.forEach((entry,i)=>{
	// 		entry.numbering = prefixNumbering + (i+1);
	// 		this._calculateNumbering(entry.subEntries, [...depth, i+1])
	// 	});
	// }


	// getTocEntries(form): ToCEntry[] {
	// 	if (form == null) { return []; }
	// 	const result: ToCEntry[] = [];

	// 	//build parent pages
	// 	(form.get('pages') as FormArray).controls.forEach((pageElement, i) => {
	// 		result.push({
	// 			id: i+'id',
	// 			label: pageElement.get('title').value,
	// 			type: ToCEntryType.Page,
	// 			form: pageElement,
	// 			numbering: (i + 1).toString(),
	// 			subEntriesType: ToCEntryType.Section,
	// 			subEntries:[],
	// 			ordinal: pageElement.get('ordinal').value
	// 		} as ToCEntry)
	// 	});


	// 	result.forEach((entry,i)=>{

	// 		const sections = entry.form.get('sections') as FormArray;

	// 		sections.controls.forEach(section=>{
	// 			const tempResults = this._buildRecursively(section as FormGroup,ToCEntryType.Section);
	// 			entry.subEntries.push(tempResults);
	// 		});

	// 	});

	// 	this._sortByOrdinal(result);
	// 	//calculate numbering
	// 	this._calculateNumbering(result);
	// 	return result;

	// }


}
