
import { Component, OnInit} from '@angular/core';
import { FormGroup, AbstractControl, FormControl, FormArray} from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { DmpStatus } from '@app/core/common/enum/dmp-status';
import { DataTableRequest } from '@app/core/model/data-table/data-table-request';
import { DmpProfileDefinition } from '@app/core/model/dmp-profile/dmp-profile';
import { DmpProfileListing } from '@app/core/model/dmp-profile/dmp-profile-listing';
import { DmpModel } from '@app/core/model/dmp/dmp';
import { UserModel } from '@app/core/model/user/user';
import { UserInfoListingModel } from '@app/core/model/user/user-info-listing';
import { BaseCriteria } from '@app/core/query/base-criteria';
import { DmpProfileCriteria } from '@app/core/query/dmp/dmp-profile-criteria';
import { GrantCriteria } from '@app/core/query/grant/grant-criteria';
import { RequestItem } from '@app/core/query/request-item';
import { AuthService } from '@app/core/services/auth/auth.service';
import { DmpProfileService } from '@app/core/services/dmp/dmp-profile.service';
import { DmpService } from '@app/core/services/dmp/dmp.service';
import { SnackBarNotificationLevel, UiNotificationService } from '@app/core/services/notification/ui-notification-service';
import { ConfirmationDialogComponent } from '@common/modules/confirmation-dialog/confirmation-dialog.component';
import { DmpEditorModel } from '@app/ui/dmp/editor/dmp-editor.model';
import { DmpFinalizeDialogComponent, DmpFinalizeDialogInput } from '@app/ui/dmp/editor/dmp-finalize-dialog/dmp-finalize-dialog.component';
import { FunderFormModel } from '@app/ui/dmp/editor/grant-tab/funder-form-model';
import { GrantTabModel } from '@app/ui/dmp/editor/grant-tab/grant-tab-model';
import { ProjectFormModel } from '@app/ui/dmp/editor/grant-tab/project-form-model';
import { BreadcrumbItem } from '@app/ui/misc/breadcrumb/definition/breadcrumb-item';
import { IBreadCrumbComponent } from '@app/ui/misc/breadcrumb/definition/IBreadCrumbComponent';
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 { TranslateService } from '@ngx-translate/core';
import * as FileSaver from 'file-saver';
import { Observable, of as observableOf, interval } from 'rxjs';
import { map, takeUntil } from 'rxjs/operators';
import { Principal } from "@app/core/model/auth/principal";
import { Role } from "@app/core/common/enum/role";
import { LockService } from '@app/core/services/lock/lock.service';
import { LockModel } from '@app/core/model/lock/lock.model';
import { Guid } from '@common/types/guid';
import { ConfigurationService } from '@app/core/services/configuration/configuration.service';
import { ExtraPropertiesFormModel } from './general-tab/extra-properties-form.model';
import { DatasetWizardEditorModel } from '@app/ui/dataset/dataset-wizard/dataset-wizard-editor.model';
import { DatasetWizardService } from '@app/core/services/dataset-wizard/dataset-wizard.service';
import { DatasetService } from '@app/core/services/dataset/dataset.service';
import { DmpToDatasetDialogComponent } from '../dmp-to-dataset/dmp-to-dataset-dialog.component';
import { GrantEditorModel } from '@app/ui/grant/editor/grant-editor.model';
import { MatomoService } from '@app/core/services/matomo/matomo-service';
import { PopupNotificationDialogComponent } from '@app/library/notification/popup/popup-notification.component';
import { CheckDeactivateBaseComponent } from '@app/library/deactivate/deactivate.component';

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

	editMode = true;
	// editMode = false;
	saving = false;

	breadCrumbs: Observable<BreadcrumbItem[]>;
	isNew = true;
	isPublic = false;
	isFinalized = false;
	hasChanges = false;
	isDiscarded = false;
	hasDmpId = false;
	isUserOwner: boolean = true;

	dmp: DmpEditorModel;
	dmpModel: DmpModel;
	formGroup: FormGroup = null;
	// datasetFormGroup: FormGroup;
	formGroupRawValue: any;
	datasetId: string = null;
	datasets = new FormArray([]);
	datasetWizardEditorModel: DatasetWizardEditorModel;
	createNewVersion;

	associatedUsers: Array<UserModel>;
	people: Array<UserInfoListingModel>;
	filteredOptions: DmpProfileListing[];
	selectedDmpProfileDefinition: DmpProfileDefinition;

	DynamicDmpFieldResolverComponent: any;
	lock: LockModel;
	lockStatus: Boolean;

	selectedTab = 0;
	step: number = 0;
	stepsBeforeDatasets: number = 4;
	maxStep: number = 4;

	scrollTop: number;
	hintErrors:boolean = false;

	constructor(
		private dmpProfileService: DmpProfileService,
		private datasetWizardService: DatasetWizardService,
		private datasetService: DatasetService,
		private dmpService: DmpService,
		private route: ActivatedRoute,
		private router: Router,
		private language: TranslateService,
		private dialog: MatDialog,
		private uiNotificationService: UiNotificationService,
		private authentication: AuthService,
		private authService: AuthService,
		private formService: FormService,
		private lockService: LockService,
		private configurationService: ConfigurationService,
		private matomoService: MatomoService
	) {
		super();
	}

	ngOnInit() {
		this.matomoService.trackPageView('DMP Editor');
		this.route.params
			.pipe(takeUntil(this._destroyed))
			.subscribe((params: Params) => {
				const itemId = params['id'];
				const publicId = params['publicId'];
				const queryParams = this.route.snapshot.queryParams;
				const tabToNav = queryParams['tab'];
				const dmpId = params['dmpId'];
				this.datasetId = queryParams['dataset'];
				// if (queryParams['step']) {	this.step = queryParams['step']; }

				const grantRequestItem: RequestItem<GrantCriteria> = new RequestItem();
				grantRequestItem.criteria = new GrantCriteria();
				const organisationRequestItem: RequestItem<BaseCriteria> = new RequestItem();
				organisationRequestItem.criteria = new BaseCriteria();

				// this.grantAutoCompleteConfiguration = {
				// 	filterFn: this.searchGrant.bind(this),
				// 	initialItems: (extraData) => this.searchGrant(''),
				// 	displayFn: (item) => item['label'],
				// 	titleFn: (item) => item['label']
				// };

				switch (tabToNav) {
					case 'general':
						this.selectedTab = 0;
						break;
					case 'grant':
						this.selectedTab = 1;
						break;
					case 'datasetDescriptions':
						this.selectedTab = 2;
						break;
					case 'peoples':
						this.selectedTab = 3;
						break;
				}
				if (itemId != null) {
					this.isNew = false;
					this.dmpService.getSingle(itemId).pipe(map(data => data as DmpModel))
						.pipe(takeUntil(this._destroyed))
						.subscribe(async data => {
							this.lockService.checkLockStatus(data.id).pipe(takeUntil(this._destroyed)).subscribe(lockStatus => {
								this.lockStatus = lockStatus;
								this.dmpModel = data;

								this.dmp = new DmpEditorModel();
								this.dmp.grant = new GrantTabModel();
								this.dmp.project = new ProjectFormModel();
								this.dmp.funder = new FunderFormModel();
								this.dmp.extraProperties = new ExtraPropertiesFormModel();
								this.dmp.fromModel(data);
								this.formGroup = this.dmp.buildForm();

								this.datasets = this.formGroup.get('datasets') as FormArray;

								this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
								this.maxStep = this.formGroup.get('datasets') ? this.maxStep + this.formGroup.get('datasets').value.length - 1 : this.maxStep;

								this.setIsUserOwner();
								if (!this.isUserOwner) {

									if(this.isUserMember()){
										this.router.navigate(['plans', 'overview', itemId]);
										return;
									}
									this.isFinalized = true;
									this.formGroup.disable();
								}

								if (this.datasetId) {
									this.step = this.formGroup.get('datasets')['controls'].findIndex((dataset) => { return this.datasetId === dataset.get('id').value; }) + this.stepsBeforeDatasets;
								}

								//this.registerFormEventsForDmpProfile(this.dmp.definition);
								if (!this.editMode || this.dmp.status === DmpStatus.Finalized || lockStatus) {
									this.isFinalized = true;
									this.formGroup.disable();
								}

								if (this.isAuthenticated) {
									if (!lockStatus) {
										this.lock = new LockModel(data.id, this.getUserFromDMP());

										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.isAuthenticated) {
									const breadCrumbs = [];
									breadCrumbs.push({
										parentComponentName: null,
										label: this.language.instant('NAV-BAR.MY-DMPS'),
										url: "/plans"
									});
									breadCrumbs.push({
										parentComponentName: 'DmpListingComponent',
										label: this.dmp.label,
										url: '/plans/edit/' + this.dmp.id,
										// notFoundResolver: [await this.grantService.getSingle(this.dmp.grant.id).map(x => ({ label: x.label, url: '/grants/edit/' + x.id }) as BreadcrumbItem).toPromise()]
									}
									);
									this.breadCrumbs = observableOf(breadCrumbs);
								}
								this.associatedUsers = data.associatedUsers;
								this.people = data.users;
								this.formGroup.valueChanges.pipe(takeUntil(this._destroyed))
									.subscribe(x => {
										this.formChanged();
									});
								if(this.lockStatus){
									this.dialog.open(PopupNotificationDialogComponent,{data:{
										title:this.language.instant('DMP-EDITOR.LOCKED.TITLE'),
										message:this.language.instant('DMP-EDITOR.LOCKED.MESSAGE')
									}, maxWidth:'30em'});
								}
							})
						});
				} else if (publicId != null) {
					this.isNew = false;
					this.isPublic = true;
					this.isFinalized = true;
					this.dmpService.getSinglePublic(publicId).pipe(map(data => data as DmpModel))
						.pipe(takeUntil(this._destroyed))
						.subscribe(async data => {
							// this.lockService.checkLockStatus(data.id).pipe(takeUntil(this._destroyed)).subscribe(lockStatus => {
							// this.lockStatus = true;
							this.dmpModel = data;

							this.dmp = new DmpEditorModel();
							this.dmp.grant = new GrantTabModel();
							this.dmp.project = new ProjectFormModel();
							this.dmp.funder = new FunderFormModel();
							this.dmp.extraProperties = new ExtraPropertiesFormModel();
							this.dmp.fromModel(data);
							this.formGroup = this.dmp.buildForm();

							// this.formGroup.get('datasets')['controls'].forEach(element => {
							// 	this.datasets.push(element);
							// });
							this.datasets = this.formGroup.get('datasets') as FormArray;
							this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
							this.maxStep = this.formGroup.get('datasets') ? this.maxStep + this.formGroup.get('datasets').value.length - 1 : this.maxStep;

							//this.registerFormEventsForDmpProfile(this.dmp.definition);
							this.formGroup.disable();
							// if (!this.isAuthenticated) {
							const breadcrumbs = [];
							breadcrumbs.push({ parentComponentName: null, label: this.language.instant('NAV-BAR.PUBLIC-DMPS').toUpperCase(), url: '/plans' });
							breadcrumbs.push({ parentComponentName: null, label: this.dmp.label, url: '/plans/publicEdit/' + this.dmp.id });
							this.breadCrumbs = observableOf(breadcrumbs);
							// this.breadCrumbs = Observable.of([
							// 	{
							// 		parentComponentName: 'DmpListingComponent',
							// 		label: this.language.instant('NAV-BAR.MY-DMPS'),
							// 		url: 'plans',
							// 		notFoundResolver: [await this.grantService.getSingle(this.dmp.grant.id).map(x => ({ label: x.label, url: '/grants/edit/' + x.id }) as BreadcrumbItem).toPromise()]
							// 	}]
							// );
							this.associatedUsers = data.associatedUsers;
							// }
							// if (!lockStatus) {
							// 	this.lock = new LockModel(data.id, this.getUserFromDMP());

							// 	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());
							// 	});
							// }
							// })
							this.formGroup.valueChanges.pipe(takeUntil(this._destroyed))
								.subscribe(x => {
									this.formChanged();
								});
						});
				} else {
					this.dmp = new DmpEditorModel();
					this.dmp.grant = new GrantTabModel();
					this.dmp.project = new ProjectFormModel();
					this.dmp.funder = new FunderFormModel();
					this.dmp.extraProperties = new ExtraPropertiesFormModel();
					this.dmp.extraProperties.visible = false;
					this.dmp.extraProperties.contact = this.authService.current().id;
					this.formGroup = this.dmp.buildForm();

					this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
					this.maxStep = this.formGroup.get('datasets') ? this.maxStep + this.formGroup.get('datasets').value.length - 1 : this.maxStep;

					this.registerFormEventsForNewItem();
					if (this.isAuthenticated) {
						this.language.get('NAV-BAR.MY-DMPS').pipe(takeUntil(this._destroyed)).subscribe(x => {
							this.breadCrumbs = observableOf([
								{
									parentComponentName: null,
									label: x,
									url: '/plans'
								},
								{
									parentComponentName: null,
									label: "CREATE NEW DMP",
									url: "/plans/new"
								}
							]);
						})
					}
					this.formGroup.valueChanges.pipe(takeUntil(this._destroyed))
						.subscribe(x => {
							this.formChanged();
						});
				}
			});

		this.route
			.queryParams
			.pipe(takeUntil(this._destroyed))
			.subscribe(params => {
				this.createNewVersion = params['clone'];
			});
	}

	copyFormControl(control: AbstractControl) {
		if (control instanceof FormControl) {
			return new FormControl(control.value);
		} else if (control instanceof FormGroup) {
			const copy = new FormGroup({});
			Object.keys(control.getRawValue()).forEach(key => {
				copy.addControl(key, this.copyFormControl(control.controls[key]));
			});
			return copy;
		} else if (control instanceof FormArray) {
			const copy = new FormArray([]);
			control.controls.forEach(control => {
				copy.push(this.copyFormControl(control));
			})
			return copy;
		}
	}

	public formChanged() {
		if (!this.isDiscarded) {
			this.hasChanges = true;
		}
	}

	isAuthenticated() {
		return this.authService.current() != null;
	}

	setIsUserOwner() {
		if (this.dmp) {
			const principal: Principal = this.authentication.current();
			this.isUserOwner = !!this.dmp.users.find(x => (x.role === Role.Owner) && (x.id === principal.id) );
		}
	}
	isUserMember(): boolean{
		try{
			const principal: Principal = this.authentication.current();
			return !!this.dmp.users.find(x => (x.role === Role.Member) && (x.id === principal.id) );
		}catch{
			return false;
		}
	}

	getUserFromDMP(): any {
		if (this.dmp) {
			const principal: Principal = this.authentication.current();
			return this.dmp.users.find(x => x.id === principal.id);
		}
	}

	registerFormEventsForNewItem() {
		this.breadCrumbs = observableOf([
			{
				parentComponentName: 'DmpListingComponent',
				label: this.language.instant('NAV-BAR.MY-DMPS'),
				url: 'plans',
			}
		]);
	}

	dmpProfileSearch(query: string) {
		let fields: Array<string> = new Array();
		var request = new DataTableRequest<DmpProfileCriteria>(0, 10, { fields: fields });
		request.criteria = new DmpProfileCriteria();
		return this.dmpProfileService.getPaged(request).pipe(map(x => x.data));
	}

	// searchGrant(query: string) {
	// 	const grantRequestItem: RequestItem<GrantCriteria> = new RequestItem();
	// 	grantRequestItem.criteria = new GrantCriteria();
	// 	grantRequestItem.criteria.like = query;
	// 	return this.grantService.getWithExternal(grantRequestItem);
	// }

	formSubmit(addNew?: boolean, showAddDatasetDialog?: boolean): void {
		this.saving = true;
		this.formService.touchAllFormFields(this.formGroup);
		// if (this.isNewDataset) {
		// 	if (!this.isDatasetFormValid) {
		// 		this.showValidationErrorsDialog();
		// 		return;
		// 	}
		// 	this.onDatasetSubmit();
		// }
		// else {
		// console.log("update ", this.formGroup);
		/*
		if (!this.isFormValid()) {
			this.showValidationErrorsDialog();
			this.hintErrors = true;
			return;
		}
		*/

		// if(!this.formval)

		if(!this._isDMPDescriptionValid()){
			const errmess = this._buildDMPDescriptionErrorMessages();
			this.showValidationErrorsDialog(undefined, errmess);
			this.hintErrors = true;
			this.saving = false;
			return;
		}
		this.onSubmit(addNew, showAddDatasetDialog);
		// }
	}

	public isFormValid() {
		return this.formGroup.valid;
		// return this.formGroup.get('label').valid && this.formGroup.get('profiles').valid &&
		// 	(this.formGroup.get('funder').get('label').valid || this.formGroup.get('funder').get('existFunder').valid) &&
		// 	(this.formGroup.get('grant').get('label').valid || this.formGroup.get('grant').get('existGrant').valid);
	}

	public isDatasetFormValid() {
		return this.formGroup.get('datasets')['controls'][0].valid;
	}

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

	}

	onSubmit(addNew?: boolean, showAddDatasetDialog?: boolean): void {
		this.scrollTop = document.getElementById('editor-form').scrollTop;
		// return;
		this.dmpService.createDmp(this.formGroup.getRawValue())
			.pipe(takeUntil(this._destroyed))
			.subscribe(
				complete => {
					this.formGroup.get('id').setValue(complete.id);
					this.formGroup.get('modified').setValue(complete.modified);
					this.hasChanges = false;
					if (showAddDatasetDialog) {
						this.addDatasetOpenDialog(complete);
					}
					if (addNew) {
						this.onCallbackSuccessAddNew(complete);
					}
					else { this.onCallbackSuccess(complete) }
				},
				error => {
					this.formGroup.get('status').setValue(DmpStatus.Draft);
					this.onCallbackError(error);
				}
			);
		// this.dmpService.createDmpWithDatasets(this.formGroup.getRawValue())
		// 	.pipe(takeUntil(this._destroyed))
		// 	.subscribe(
		// 		complete => {
		// 			if (showAddDatasetDialog) {
		// 				this.addDatasetOpenDialog(complete);
		// 			}
		// 			else if (this.step < this.stepsBeforeDatasets) { this.onCallbackSuccess(complete) }
		// 			else { this.onCallbackSuccess(complete, this.datasetId) }
		// 		},
		// 		error => {
		// 			this.formGroup.get('status').setValue(DmpStatus.Draft);
		// 			this.onCallbackError(error);
		// 		}
		// 	)
	}

	onDatasetSubmit(): void {
		this.datasetWizardService.createDataset(this.formGroup.get('datasets')['controls'][0].getRawValue())
			.pipe(takeUntil(this._destroyed))
			.subscribe(
				data => {
					this.onCallbackSuccess(this.formGroup.get('datasets')['controls'][0].get('id').value);
				},
				error => this.onCallbackError(error)
			);
	}

	onCallbackSuccess(dmp?: DmpModel, datasetId?: string): void {

		// On save keep editor position
		this.uiNotificationService.snackBarNotification(this.isNew ? this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-CREATION') : this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-UPDATE'), SnackBarNotificationLevel.Success);
		if (dmp) {
			let dmpEditorModel: DmpEditorModel;
			dmpEditorModel = new DmpEditorModel();
			dmpEditorModel.grant = new GrantTabModel();
			dmpEditorModel.project = new ProjectFormModel();
			dmpEditorModel.funder = new FunderFormModel();
			dmpEditorModel.extraProperties = new ExtraPropertiesFormModel();
			dmpEditorModel.fromModel(dmp);
			this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
			this.associatedUsers = dmp.associatedUsers;
			this.people = dmp.users;

			setTimeout(() => { this.formGroup = null; });
			setTimeout(() => { this.formGroup = dmpEditorModel.buildForm(); });
			setTimeout(() => { document.getElementById('editor-form').scrollTop = this.scrollTop; });
			this.saving = false;
			this.isNew = false;
		} else {
			this.router.navigate(['/reload']).then(() => { this.router.navigate(['/plans']); });
		}

		// Uncomment to not keep editor position on save
		// if (dmp.id != null) {
		// 	datasetId ? this.router.navigate(['/reload']).then(() => { this.router.navigate(['/plans', 'edit', dmp.id], { queryParams: { dataset: datasetId } }); }) : this.router.navigate(['/reload']).then(() => { this.router.navigate(['/plans', 'edit', dmp.id]); })
		// } else {
		// 	this.router.navigate(['/reload']).then(() => { this.router.navigate(['/plans']); });
		// }
	}

	onCallbackError(error: any) {
		this.uiNotificationService.snackBarNotification(error.error.message, SnackBarNotificationLevel.Error);
		this.setErrorModel(error.error);
		this.saving = false;
		//this.validateAllFormFields(this.formGroup);
	}

	onCallbackSuccessAddNew(dmp?: DmpModel) {
		// this.editDataset(dmp.id, true, this.isNew && !this.formGroup.get('datasets').value.length);
		this.editDataset(dmp.id, true, false);
		this.saving = false;
	}

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

	public cancel(id: String): void {
		if (id != null) {
			this.lockService.unlockTarget(this.dmp.id).pipe(takeUntil(this._destroyed)).subscribe(
				complete => {
					this.router.navigate(['/plans/overview/' + id]);
				},
				error => {
					this.formGroup.get('status').setValue(DmpStatus.Draft);
					this.onCallbackError(error);
				}

			)

		} else {
			this.router.navigate(['/plans']);
		}
	}

	public invite(): void {
		this.router.navigate(['/invite/' + this.dmp.id]);
	}

	public delete(): 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.dmpService.delete(this.dmp.id)
					.pipe(takeUntil(this._destroyed))
					.subscribe(
						complete => { this.onCallbackSuccess() },
						error => this.onDeleteCallbackError(error)
					);
			}
		});
	}
	onDeleteCallbackError(error) {
		this.uiNotificationService.snackBarNotification(error.error.message ? error.error.message : this.language.instant('GENERAL.SNACK-BAR.UNSUCCESSFUL-DELETE'), SnackBarNotificationLevel.Error);
	}

	displayWith(item: any) {
		if (!item) { return null; }
		return item['label'];
	}

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

	redirectToDatasets() {
		this.router.navigate(['datasets'], { queryParams: { dmpId: this.dmp.id } });
	}

	newVersion(id: String, label: String) {
		this.router.navigate(['/plans/new_version/' + id, { dmpLabel: label }]);
	}

	// OLD CLONE VERSION
	// clone(id: String) {
	// 	this.router.navigate(['/plans/clone/' + id]);
	// }

	// NEW CLONE VERSION
	// clone(dmp: DmpListingModel) {
	// 	this.openCloneDialog();
	// }

	// openCloneDialog() {
	// 	const dialogRef = this.dialog.open(CloneDialogComponent, {
	// 		maxWidth: '700px',
	//      maxHeight: '80vh',
	// 		data: {
	// 			formGroup: this.formGroup,
	// 			datasets: this.formGroup.get('datasets').value,
	// 			confirmButton: this.language.instant('DMP-EDITOR.CLONE-DIALOG.CLONE'),
	// 			cancelButton: this.language.instant('DMP-EDITOR.CLONE-DIALOG.CANCEL'),
	// 		}
	// 	});
	// 	dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
	// 		if (result) {
	// 			this.dmpService.clone(this.formGroup.getRawValue(), this.formGroup.get('id').value)
	// 			.pipe(takeUntil(this._destroyed))
	// 			.subscribe(
	// 				complete => this.onCloneCallbackSuccess(complete),
	// 				error => this.onCloneCallbackError(error)
	// 			);
	// 		}
	// 	});
	// }

	viewVersions(rowId: String, rowLabel: String) {
		this.router.navigate(['/plans/versions/' + rowId], { queryParams: { groupLabel: rowLabel } });
	}

	downloadXml(id: string) {
		this.dmpService.downloadXML(id)
			.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);
			});
	}

	downloadDocx(id: string) {
		this.dmpService.downloadDocx(id)
			.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);
			});
	}

	downloadPDF(id: string) {
		this.dmpService.downloadPDF(id)
			.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);
			});
	}

	downloadJson(id: string) {
		this.dmpService.downloadJson(id)
			.pipe(takeUntil(this._destroyed))
			.subscribe(response => {
				const blob = new Blob([response.body], { type: 'application/json' });
				const filename = this.getFilenameFromContentDispositionHeader(response.headers.get('Content-Disposition'));
				FileSaver.saveAs(blob, filename);
			}, async error => {
				this.onExportCallbackError(error);
			});
	}

	async onExportCallbackError(error: any) {
		const errorJsonText = await error.error.text();
		const errorObj = JSON.parse(errorJsonText);
		this.uiNotificationService.snackBarNotification(errorObj.message, SnackBarNotificationLevel.Error);
	}

	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 enableForm() {
		if (this.formGroup.get('status').value !== DmpStatus.Finalized) {
			this.editMode = true;
			this.formGroup.enable();
		}
		//else {
		// 	this.dmpService.unlock(this.formGroup.get('id').value)
		// 		.pipe(takeUntil(this._destroyed))
		// 		.subscribe(x => {
		// 			this.editMode = true;
		// 			this.formGroup.get('status').patchValue(DmpStatus.Draft);
		// 			this.formGroup.enable();
		// 		});
		// }
	}

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

	save() {
		this.formSubmit(true);
	}

	//checks if the dpm is valid not taking into account the datasets validity
	private _isDMPDescriptionValid():boolean{

		const form: FormGroup = this.formGroup;
		if(form.controls){
			return Object.keys(form.controls)
					.map(controlName=>{//get validity of each control
						if(controlName === 'datasets'){//we dont care if datasets are valid
							return true;
						}
						return !form.get(controlName).invalid;//!! in case the control is disabled, we consider it valid
					})
					.reduce((isFormValid,isControlValid)=>{//aggregate validities
						return isControlValid && isFormValid;
					}, true);
		}
		return true;
	}

	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 _buildDMPDescriptionErrorMessages(): string[]{//not including datasets
		const errmess: string[] = [];
		Object.keys(this.formGroup.controls).forEach(controlName=>{
			if(controlName != 'datasets' && 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;
	}





	addDataset() {
		this.saving = true;

		if(!this._isDMPDescriptionValid()){
			const errmess = this._buildDMPDescriptionErrorMessages();
			this.showValidationErrorsDialog(undefined, errmess);
			this.hintErrors = true;
			this.saving = false;
			return;
		}


		// const showDialog = this.hasProfile() && this.isNew;

		this.onSubmit(true, false);
		// this.formSubmit(true, false);




		// Add dataset to list
		// if (!this.formGroup.get('datasets')) {
		// 	this.formGroup.addControl('datasets', new FormBuilder().array(new Array<FormControl>()));
		// }
		// this.formGroup.get('datasets')['controls'].push(new DatasetWizardEditorModel().buildForm());
		// this.datasets = this.formGroup.get('datasets') as FormArray;
		// this.step = this.stepsBeforeDatasets + this.formGroup.get('datasets')['controls'].length - 1;
		// this.maxStep = this.maxStep + this.formGroup.get('datasets')['controls'].length - 1;
	}

	hasProfile(): boolean {
		return this.formGroup.get('profiles') && this.formGroup.get('profiles').value && this.formGroup.get('profiles').value.length > 0;
	}

	addDatasetOpenDialog(dmp: DmpModel) {
		const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
			maxWidth: '500px',
			restoreFocus: false,
			data: {
				message: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ADD-DATASET'),
				confirmButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CONFIRM'),
				cancelButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.NO'),
				isDeleteConfirmation: false
			}
		});

		dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
			if (result) {
				// this.router.navigate(['datasets/new/' + id]);
				this.addDataset();
			} else {
				dmp.id != null ? this.router.navigate(['/plans', 'edit', dmp.id]) : this.router.navigate(['/plans']);
			}
		});
	}

	editDataset(id: string, isNew: boolean, showModal:boolean = false) {


		if(showModal){
			const dialogRef = this.dialog.open(DmpToDatasetDialogComponent, {
				width: '500px',
				autoFocus: false,
				restoreFocus: false,
			});
			dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
				if (result) {
					if (isNew) {
						this.router.navigate(['/datasets', 'new', id]);
					} else {
						this.router.navigate(['/datasets', 'edit', id]);
					}
				}
			});
		}else{
			if (isNew) {
				this.router.navigate(['/datasets', 'new', id]);
			} else {
				this.router.navigate(['/datasets', 'edit', id]);
			}

		}


	}

	saveAndFinalize() {
		const dialogInputModel: DmpFinalizeDialogInput = {
			dmpLabel: this.formGroup.get('label').value,
			dmpDescription: this.formGroup.get('description').value,
			datasets: this.formGroup.get('datasets').value.map(x => {
				return { label: x.label, id: x.id, status: x.status };
			})
		}

		const dialogRef = this.dialog.open(DmpFinalizeDialogComponent, {
			maxWidth: '500px',
			restoreFocus: false,
			autoFocus: false,
			data: {
				dialogInputModel: dialogInputModel,
				message: this.language.instant('GENERAL.CONFIRMATION-DIALOG.FINALIZE-ITEM'),
				confirmButton: this.language.instant('DMP-FINALISE-DIALOG.SUBMIT'),
				cancelButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CANCEL'),
			}
		});
		dialogRef.afterClosed()
			.pipe(takeUntil(this._destroyed))
			.subscribe(result => {
				if (result && !result.cancelled) {
					this.formGroup.get('status').setValue(DmpStatus.Finalized);
					this.formGroup.get('datasetsToBeFinalized').setValue(result.datasetsToBeFinalized);
					this.formSubmit(false);
					//this.router.navigate(['/plans/overview/' + this.formGroup.get('id').value]);
					dialogRef.close();
				}
			});
	}

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

	public changeStep(index: number, dataset?: FormControl) {
		this.step = index;
		this.resetScroll();
		if (dataset) { this.datasetId = dataset.get('id').value };
	}

	public nextStep() {
		this.step = this.step < this.maxStep ? this.step + 1 : this.step;
		this.resetScroll();
		if (this.step >= this.stepsBeforeDatasets) {
			this.datasetId = this.datasets.at(this.step - this.stepsBeforeDatasets).get('id').value;
		}
	}

	public previousStep() {
		this.step = this.step !== 0 ? this.step - 1 : this.step;
		this.resetScroll();
		if (this.step >= this.stepsBeforeDatasets) {
			this.datasetId = this.datasets.at(this.step - this.stepsBeforeDatasets).get('id').value;
		}
	}

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

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

	public discardChanges() {
		this.isDiscarded = true;
		this.hasChanges = false;
		if (!this.isNew) {
			let grantControl;
			if (this.formGroup.get('grant').get('existGrant')) {
				grantControl = new GrantTabModel();
				grantControl.fromModel(this.formGroup.get('grant').get('existGrant').value);
			} else {
				grantControl = new GrantEditorModel();
				grantControl.fromModel(this.formGroup.get('grant').value);
			}
			grantControl.buildForm()

			this.formGroup.patchValue(JSON.parse(JSON.stringify(this.formGroupRawValue)));

			if (this.formGroup.get('grant').get('existGrant')) {
				this.formGroup.get('grant').get('existGrant').setValue(grantControl.existGrant);
			} else {
				this.formGroup.get('grant').setValue(grantControl);
			}
		} else {
			this.formGroup.reset();
			this.formGroup.get("status").setValue(DmpStatus.Draft);
			this.formGroup.get('extraProperties').get('visible').setValue(false);
			this.formGroup.get('extraProperties').get('contact').setValue(this.authService.current().id);
			this.formGroup.get('associatedUsers').setValue([]);
		}
		this.isDiscarded = false;
	}

	public removeDataset(datasetId: string, index: number) {
		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) {
				if (datasetId) {
					this.datasetService.delete(datasetId)
						.pipe(takeUntil(this._destroyed))
						.subscribe(
							complete => {
								this.onDeleteCallbackSuccess();
							},
							error => this.onDeleteCallbackError(error)
						);
				}
				this.formGroup.get('datasets')['controls'].splice(index, 1);
				this.step = 0;
			}
		});
	}

	onDeleteCallbackSuccess(): void {
		this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-DELETE'), SnackBarNotificationLevel.Success);
		this.dmp.id != null ? this.router.navigate(['/plans', 'edit', this.dmp.id]) : this.router.navigate(['/plans']);
	}

	mainInfoValid(): boolean {
		if (this.formGroup.get('label').valid) {
			if (this.formGroup.get('publicDate')) {
				if (this.formGroup.get('publicDate').valid) {
					return true;
				} else if (this.formGroup.get('publicDate').invalid) {
					return false
				}
			} else {
				return true;
			}
		} else {
			return false;
		}
	}

	fundingInfoValid(): boolean {
		return this.formGroup.get('funder') && this.formGroup.get('funder').valid && this.formGroup.get('grant') && this.formGroup.get('grant').valid;
	}

	datasetInfoValid(): boolean {
		return this.formGroup.get('profiles') && this.formGroup.get('profiles').valid && this.formGroup.get('profiles').value.length > 0;
	}

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