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

@Component({
	selector: 'app-recent-edited-dmp-activity',
	templateUrl: './recent-edited-dmp-activity.component.html',
	styleUrls: ['./recent-edited-dmp-activity.component.css']
})
export class RecentEditedDmpActivityComponent extends BaseComponent implements OnInit {

	@Output() totalCountDmps: EventEmitter<any> = new EventEmitter();

	dmpActivities: DmpListingModel[];
	datasetActivities: DatasetListingModel[];
	dmpModel: DmpEditorModel;
	recentActivityTypeEnum = RecentActivityType;
	isDraft: boolean;

	totalCount: number;
	startIndex: number = 0;
	pageSize: number = 5;
	dmpFormGroup: FormGroup;
	public formGroup = new FormBuilder().group({
		like: new FormControl(),
		order: new FormControl()
	});
	publicMode = false;

	order = RecentActivityOrder;

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

	ngOnInit() {
		this.matomoService.trackPageView('Recent DMP Activity');
		if (this.isAuthenticated()) {
			// const fields: Array<string> = ["-modified"];
			this.formGroup.get('order').setValue(this.order.MODIFIED);
			const fields: Array<string> = [((this.formGroup.get('order').value === 'status') || (this.formGroup.get('order').value === 'label') ? '+' : "-") + this.formGroup.get('order').value];
			const dmpDataTableRequest: DataTableRequest<DmpCriteria> = new DataTableRequest(0, 5, { fields: fields });
			dmpDataTableRequest.criteria = new DmpCriteria();
			dmpDataTableRequest.criteria.like = "";
			this.dmpService
				.getPaged(dmpDataTableRequest, "listing")
				.pipe(takeUntil(this._destroyed))
				.subscribe(response => {
					this.dmpActivities = response.data;
					this.totalCount = response.totalCount;
					this.totalCountDmps.emit(this.dmpActivities.length);
					// this.totalCount < this.pageSize ? this.totalCountDmps.emit(response.totalCount) : this.totalCountDmps.emit(this.pageSize);
					// this.totalCountDmps.emit(this.totalCount);
					// this.dmpActivities.forEach(dmpActivity => {
					// 	const recentActivity: RecentActivity = {
					// 		activityData: dmpActivity,
					// 		activityType: RecentActivityType.Dmp
					// 	};
					// 	this.allRecentActivities.push(recentActivity)
					// })
				});
			this.formGroup.get('like').valueChanges
				.pipe(takeUntil(this._destroyed), debounceTime(500))
				.subscribe(x => this.refresh());
			this.formGroup.get('order').valueChanges
				.pipe(takeUntil(this._destroyed))
				.subscribe(x => this.refresh());
			// const datasetDataTableRequest: DataTableRequest<DatasetCriteria> = new DataTableRequest(0, 5, { fields: fields });
			// datasetDataTableRequest.criteria = new DatasetCriteria();
			// datasetDataTableRequest.criteria.like = "";
			// this.datasetService
			// 	.getPaged(datasetDataTableRequest)
			// 	.subscribe(response => {
			// 		this.datasetActivities = response.data;
			// 		this.datasetActivities.forEach(datasetActivity => {
			// 			const recentActivity: RecentActivity = {
			// 				activityData: datasetActivity,
			// 				activityType: RecentActivityType.Dataset
			// 			};
			// 			this.allRecentActivities.push(recentActivity)
			// 		})
			// 	});
		} else {
			this.publicMode = true;
			this.formGroup.get('order').setValue(this.order.PUBLISHED);
			const dataTableRequest = this.setPublicDataTableRequest();
			this.dmpService.getPaged(dataTableRequest, "listing").pipe(takeUntil(this._destroyed)).subscribe(response => {
				if (!response) { return []; }
				this.dmpActivities = response.data;
				this.totalCount = response.totalCount;
				this.totalCountDmps.emit(this.dmpActivities.length);
			});
			this.formGroup.get('like').valueChanges
				.pipe(takeUntil(this._destroyed), debounceTime(500))
				.subscribe(x => this.refresh());
			this.formGroup.get('order').valueChanges
				.pipe(takeUntil(this._destroyed))
				.subscribe(x => this.refresh());
		}
	}

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

	private setPublicDataTableRequest(fields?: Array<string>): DataTableRequest<DmpCriteria> {
		const dmpCriteria = new DmpCriteria();
		dmpCriteria.allVersions = false;
		dmpCriteria.isPublic = true;
		dmpCriteria.onlyPublic = true;
		dmpCriteria.like = this.formGroup.get("like").value ? this.formGroup.get("like").value : "";
		if (!fields) {
			fields = new Array<string>('-publishedAt');
		}
		const dataTableRequest: DataTableRequest<DmpCriteria> = new DataTableRequest(this.startIndex, this.pageSize, { fields: fields });
		dataTableRequest.criteria = dmpCriteria;
		return dataTableRequest;
	}

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

	editClicked(dmp: DmpListingModel) {
		this.router.navigate(['/plans/edit/' + dmp.id]);
	}

	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.dmpFormGroup.get('id').value)
						.pipe(takeUntil(this._destroyed))
						.subscribe(
							complete => this.onCloneOrNewVersionCallbackSuccess(complete),
							error => this.onCloneOrNewVersionCallbackError(error)
						);
				} else if (isNewVersion) {
					this.dmpService.newVersion(this.dmpFormGroup.getRawValue(), this.dmpFormGroup.get('id').value)
						.pipe(takeUntil(this._destroyed))
						.subscribe(
							complete => this.onCloneOrNewVersionCallbackSuccess(complete),
							error => this.onCloneOrNewVersionCallbackError(error)
						);
				}
			}
		});
	}

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

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

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

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

	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 ? this.language.instant(error.error.message) : this.language.instant('GENERAL.SNACK-BAR.UNSUCCESSFUL-DELETE'), SnackBarNotificationLevel.Error);
	}

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

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

	redirect(id: string) {
		if (this.isAuthenticated()) {
			this.router.navigate(['../plans/overview/' + id]);
		} else {
			this.router.navigate(['../explore-plans/publicOverview', id]);
		}
	}

	navigateToUrl(id: string): string[] {
		if (this.isAuthenticated()) {
			return ['../plans/overview/' + id];
		} else {
			return ['../explore-plans/publicOverview', id];
		}
	}

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

	// dmpProfileDisplay(value: any) {
	// 	if (value != null) {
	// 		return value;
	// 	}
	// 	else {
	// 		return "--";
	// 	}
	// }

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

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

	viewVersions(rowId: String, rowLabel: String, activity: DmpListingModel) {
		if (activity.public && !this.isUserOwner(activity)) {
			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 } });
		}
	}

	refresh(): void {
		const fields: Array<string> = [((this.formGroup.get('order').value === 'status') || (this.formGroup.get('order').value === 'label') ? '+' : "-") + this.formGroup.get('order').value];
		this.startIndex = 0;
		const dmpDataTableRequest = this.isAuthenticated() ? new DataTableRequest<DmpCriteria>(this.startIndex, this.pageSize, { fields: fields }) : this.setPublicDataTableRequest(fields);
		if (this.isAuthenticated()) {
			dmpDataTableRequest.criteria = new DmpCriteria();
			dmpDataTableRequest.criteria.like = this.formGroup.get("like").value ? this.formGroup.get("like").value : "";
		}
		this.dmpService
			.getPaged(dmpDataTableRequest, "listing")
			.subscribe(response => {
				this.dmpActivities = response.data;
				this.totalCount = response.totalCount;
				this.totalCountDmps.emit(this.dmpActivities.length);
			});
	}

	public loadMore() {
		this.startIndex = this.startIndex + this.pageSize;

		const fields: Array<string> = [((this.formGroup.get('order').value === 'status') || (this.formGroup.get('order').value === 'label') ? '+' : "-") + this.formGroup.get('order').value];
		const request = this.isAuthenticated() ? new DataTableRequest<DmpCriteria>(this.startIndex, this.pageSize, { fields: fields }) : this.setPublicDataTableRequest(fields);
		if (this.isAuthenticated()) {
			request.criteria = new DmpCriteria();
			request.criteria.like = this.formGroup.get("like").value ? this.formGroup.get("like").value : "";
		}

		this.dmpService.getPaged(request, "listing").pipe(takeUntil(this._destroyed)).subscribe(result => {
			if (!result) { return []; }
			// this.dmpActivities = this.dmpActivities.concat(result.data);
			this.dmpActivities = this.dmpActivities.length > 0 ? this.mergeTwoSortedLists(this.dmpActivities, result.data, this.formGroup.get('order').value) : result.data;
			this.totalCountDmps.emit(this.dmpActivities.length);
		});

	}

	private mergeTwoSortedLists(arr1: DmpListingModel[], arr2: DmpListingModel[], order: string): DmpListingModel[] {
		let merged = [];
		let index1 = 0;
		let index2 = 0;
		let current = 0;

		while (current < (arr1.length + arr2.length)) {

			let isArr1Depleted = index1 >= arr1.length;
			let isArr2Depleted = index2 >= arr2.length;

			if (order === 'modified') {
				if (!isArr1Depleted && (isArr2Depleted || (new Date(arr1[index1].modifiedTime) > new Date(arr2[index2].modifiedTime)))) {
					merged[current] = arr1[index1];
					index1++;
				} else {
					merged[current] = arr2[index2];
					index2++;
				}
			} else if (order === 'created') {
				if (!isArr1Depleted && (isArr2Depleted || (new Date(arr1[index1].creationTime) > new Date(arr2[index2].creationTime)))) {
					merged[current] = arr1[index1];
					index1++;
				} else {
					merged[current] = arr2[index2];
					index2++;
				}
			} else if (order === 'label') {
				if (!isArr1Depleted && (isArr2Depleted || (arr1[index1].label.localeCompare(arr2[index2].label)))) {
					merged[current] = arr1[index1];
					index1++;
				} else {
					merged[current] = arr2[index2];
					index2++;
				}
			} else if (order === 'status') {
				if (!isArr1Depleted && (isArr2Depleted || (arr1[index1].status < arr2[index2].status))) {
					merged[current] = arr1[index1];
					index1++;
				} else {
					merged[current] = arr2[index2];
					index2++;
				}
			} else if (order === "publishedAt") {
				if (!isArr1Depleted && (isArr2Depleted || (new Date(arr1[index1].publishedAt) > new Date(arr2[index2].publishedAt)))) {
					merged[current] = arr1[index1];
					index1++;
				} else {
					merged[current] = arr2[index2];
					index2++;
				}
			}
			current++;
		}
		return merged;
	}

	// advancedClicked(dmp: DmpListingModel) {
	// 	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(dmp.id);
	// 		} else if (result == "xml") {
	// 			this.downloadXml(dmp.id);
	// 		} else if (result == "doc") {
	// 			this.downloadDocx(dmp.id);
	// 		} else if (result == "json") {
	// 			this.downloadJson(dmp.id)
	// 		}
	// 	});
	// }
}
