import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { DmpListingModel } from '../../../../core/model/dmp/dmp-listing';
import { MatDialog } from '@angular/material/dialog';
import { DmpInvitationDialogComponent } from '../../invitation/dmp-invitation-dialog.component';
import { Router, ActivatedRoute } from '@angular/router';
import { DatasetService } from '../../../../core/services/dataset/dataset.service';
import { AuthService } from '../../../../core/services/auth/auth.service';
import { Principal } from '../../../../core/model/auth/principal';
import { LangChangeEvent, TranslateService } from '@ngx-translate/core';
import { DmpStatus } from '../../../../core/common/enum/dmp-status';
import { EnumUtils } from '@app/core/services/utilities/enum-utils.service';
import { DmpService } from '@app/core/services/dmp/dmp.service';
import { takeUntil, map } from 'rxjs/operators';
import { BaseComponent } from '@common/base/base.component';
import * as FileSaver from 'file-saver';
import { ConfirmationDialogComponent } from '@common/modules/confirmation-dialog/confirmation-dialog.component';
import { UiNotificationService, SnackBarNotificationLevel } from '@app/core/services/notification/ui-notification-service';
import { Role } from '@app/core/common/enum/role';
import { LockService } from '@app/core/services/lock/lock.service';
import { Location } from '@angular/common';
import { DmpModel } from '@app/core/model/dmp/dmp';
import { FormGroup } from '@angular/forms';
import { DmpEditorModel } from '../../editor/dmp-editor.model';
import { CloneDialogComponent } from '../../clone/clone-dialog/clone-dialog.component';
import { ProjectFormModel } from '../../editor/grant-tab/project-form-model';
import { FunderFormModel } from '../../editor/grant-tab/funder-form-model';
import { ExtraPropertiesFormModel } from '../../editor/general-tab/extra-properties-form.model';
import { GrantTabModel } from '../../editor/grant-tab/grant-tab-model';
import { MatomoService } from '@app/core/services/matomo/matomo-service';
import { HttpClient } from '@angular/common/http';

@Component({
	selector: 'app-dmp-listing-item-component',
	templateUrl: './dmp-listing-item.component.html',
	styleUrls: ['./dmp-listing-item.component.scss'],
})
export class DmpListingItemComponent extends BaseComponent implements OnInit {

	@Input() dmp: DmpListingModel;
	@Input() showDivider: boolean = true;
	@Input() isPublic: boolean;
	@Output() onClick: EventEmitter<DmpListingModel> = new EventEmitter();

	isDraft: boolean;
	isFinalized: boolean;
	isPublished: boolean;
	dmpModel: DmpEditorModel;
	dmpFormGroup: FormGroup;

	constructor(
		private router: Router,
		private dialog: MatDialog,
		private authentication: AuthService,
		public enumUtils: EnumUtils,
		private dmpService: DmpService,
		private language: TranslateService,
		private uiNotificationService: UiNotificationService,
		private lockService: LockService,
		private location: Location,
		private httpClient: HttpClient,
		private matomoService: MatomoService) {
		super();
	}

	ngOnInit() {
		this.matomoService.trackPageView('DMP Listing Item');
		if (this.dmp.status == DmpStatus.Draft) {
			this.isDraft = true;
			this.isFinalized = false;
			this.isPublished = false;
		}
		else if (this.dmp.status == DmpStatus.Finalized) {
			this.isDraft = false;
			this.isFinalized = true;
			this.isPublished = false;
			if (this.dmp.public == true) { this.isPublished = true }
		}
	}

	public isAuthenticated(): boolean {
		return !(!this.authentication.current());
	}

	openShareDialog(rowId: any, rowName: any) {
		const dialogRef = this.dialog.open(DmpInvitationDialogComponent, {
			// height: '250px',
			// width: '700px',
			autoFocus: false,
			restoreFocus: false,
			data: {
				dmpId: rowId,
				dmpName: rowName
			}
		});
	}

	editClicked(dmpId: String) {
		this.router.navigate(['/plans/edit/' + dmpId]);
	}

	showDatasets(rowId: String, rowLabel: String) {
		this.router.navigate(['/datasets/dmp/' + rowId, { dmpLabel: rowLabel }]);
	}

	viewVersions(rowId: String, rowLabel: String, dmp: DmpListingModel) {
		if (dmp.public && !this.isUserOwner(dmp)) {
			let url = this.router.createUrlTree(['/explore-plans/versions/', rowId, { groupLabel: rowLabel }]);
			window.open(url.toString(), '_blank');
			// this.router.navigate(['/explore-plans/versions/' + rowId], { queryParams: { groupLabel: rowLabel } });
		} else {
			let url = this.router.createUrlTree(['/plans/versions/', rowId, { groupLabel: rowLabel }]);
			window.open(url.toString(), '_blank');
			// this.router.navigate(['/plans/versions/' + rowId], { queryParams: { groupLabel: rowLabel } });
		}
	}

	// itemClicked() {
	// 	this.onClick.emit(this.dmp);
	// }

	// grantClicked(grantId: String) {
	// 	this.router.navigate(['/grants/edit/' + grantId]);
	// }

	// datasetClicked(dmpId: string) {
	// 	this.router.navigate(['/plans/edit/' + dmpId], { queryParams: { tab: "datasetDescriptions" } });
	// }

	roleDisplay(value: any) {
		const principal: Principal = this.authentication.current();
		let role: number;
		if (principal) {
			value.forEach(element => {
				if (principal.id === element.id) {
					role = element.role;
				}
			});
		}
		if (role === 0) {
			return this.language.instant('DMP-LISTING.OWNER');
		}
		else if (role === 1) {
			return this.language.instant('DMP-LISTING.MEMBER');
		}
		else {
			return this.language.instant('DMP-LISTING.OWNER');
		}
	}

	isUserDMPRelated() {
		const principal: Principal = this.authentication.current();
		let isRelated: boolean = false;
		if (this.dmp && principal) {
			this.dmp.users.forEach(element => {
				if (element.id === principal.id) {
					isRelated = true;
				}
			})
		}
		return isRelated;
	}

	cloneOrNewVersionClicked(dmp: DmpListingModel, isNewVersion: boolean) {
		this.dmpService.getSingle(dmp.id).pipe(map(data => data as DmpModel))
			.pipe(takeUntil(this._destroyed))
			.subscribe(data => {
				this.dmpModel = new DmpEditorModel();
				this.dmpModel.grant = new GrantTabModel();
				this.dmpModel.project = new ProjectFormModel();
				this.dmpModel.funder = new FunderFormModel();
				this.dmpModel.extraProperties = new ExtraPropertiesFormModel();
				this.dmpModel.fromModel(data);
				this.dmpModel.status = DmpStatus.Draft;
				this.dmpFormGroup = this.dmpModel.buildForm();

				if (!isNewVersion) {
					this.dmpFormGroup.get('label').setValue(dmp.label + " New");
				}
				this.openCloneDialog(isNewVersion);
			});
	}

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

	// newVersion(id: String, label: String) {
	// 	let url = this.router.createUrlTree(['/plans/new_version/', id, { dmpLabel: label }]);
	// 	window.open(url.toString(), '_blank');
	// }

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

	deleteClicked(id: string) {
		this.lockService.checkLockStatus(id).pipe(takeUntil(this._destroyed))
			.subscribe(lockStatus => {
				if (!lockStatus) {
					this.openDeleteDialog(id);
				} else {
					this.openLockedByUserDialog();
				}
			});
	}

	openDeleteDialog(id: string) {
		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(id)
					.pipe(takeUntil(this._destroyed))
					.subscribe(
						complete => this.onDeleteCallbackSuccess(),
						error => this.onDeleteCallbackError(error)
					);
			}
		});
	}

	openLockedByUserDialog() {
		const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
			maxWidth: '400px',
			restoreFocus: false,
			data: {
				message: this.language.instant('DMP-EDITOR.ACTIONS.LOCK')
			}
		});
	}

	isDraftDmp(activity: DmpListingModel) {
		return activity.status == DmpStatus.Draft;
	}

	reloadPage(): void {
		const path = this.location.path();
		this.router.navigateByUrl('/reload', { skipLocationChange: true }).then(() => {
			this.router.navigate([path]);
		});
	}

	onDeleteCallbackSuccess(): void {
		this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-DELETE'), SnackBarNotificationLevel.Success);
		this.reloadPage();
	}

	onDeleteCallbackError(error) {
		this.uiNotificationService.snackBarNotification(error.error.message ? error.error.message : this.language.instant('GENERAL.SNACK-BAR.UNSUCCESSFUL-DELETE'), SnackBarNotificationLevel.Error);
	}

	onCallbackSuccess(): void {
		this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-UPDATE'), SnackBarNotificationLevel.Success);
		this.router.navigate(['/plans']);
	}

	onCloneOrNewVersionCallbackSuccess(cloneId: String): void {
		this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-UPDATE'), SnackBarNotificationLevel.Success);
		this.router.navigate(['/plans/edit/', cloneId]);
	}

	onCloneOrNewVersionCallbackError(error: any) {
		this.uiNotificationService.snackBarNotification(error.error.message ? error.error.message : this.language.instant('GENERAL.SNACK-BAR.UNSUCCESSFUL-UPDATE'), SnackBarNotificationLevel.Error);
	}

	isUserOwner(activity: DmpListingModel): boolean {
		const principal: Principal = this.authentication.current();
		if (principal) return !!activity.users.find(x => (x.role === Role.Owner) && (principal.id === x.id));
	}
}
