
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { ActivatedRoute, Router } from '@angular/router';
import { DataTableRequest } from '@app/core/model/data-table/data-table-request';
import { DmpListingModel } from '@app/core/model/dmp/dmp-listing';
import { GrantListingModel } from '@app/core/model/grant/grant-listing';
import { DmpCriteria } from '@app/core/query/dmp/dmp-criteria';
import { DmpService } from '@app/core/services/dmp/dmp.service';
import { EnumUtils } from '@app/core/services/utilities/enum-utils.service';
import { DmpInvitationDialogComponent } from '@app/ui/dmp/invitation/dmp-invitation.component';
import { DmpCriteriaComponent } from '@app/ui/dmp/listing/criteria/dmp-criteria.component';
import { BreadcrumbItem } from '@app/ui/misc/breadcrumb/definition/breadcrumb-item';
import { IBreadCrumbComponent } from '@app/ui/misc/breadcrumb/definition/IBreadCrumbComponent';
import { BaseComponent } from '@common/base/base.component';
import { TranslateService } from '@ngx-translate/core';
import { Observable, of as observableOf } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { GrantService } from "@app/core/services/grant/grant.service";

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

	@ViewChild(MatPaginator, { static: true }) _paginator: MatPaginator;
	@ViewChild(MatSort, { static: false }) sort: MatSort;
	@ViewChild(DmpCriteriaComponent, { static: true }) criteria: DmpCriteriaComponent;

	breadCrumbs: Observable<BreadcrumbItem[]> = observableOf([{ parentComponentName: null, label: 'DMPs', url: "/plans" }]);
	itemId: string;
	grantId: string;
	showGrant: boolean;
	titlePrefix: string;
	totalCount: number;
	listingItems: DmpListingModel[] = [];
	allVersions: boolean = false;
	groupLabel: string;

	constructor(
		private dmpService: DmpService,
		private router: Router,
		private route: ActivatedRoute,
		private dialog: MatDialog,
		public enumUtils: EnumUtils,
		private language: TranslateService,
		private grantService: GrantService
	) {
		super();
	}

	ngOnInit() {
		this.route.params
			.pipe(takeUntil(this._destroyed))
			.subscribe(async params => {
				let grantLabel;
				if (params['grantId']) {
					this.grantId = params['grantId'];
					this.showGrant = true;
					this.grantService.getSingle(this.grantId)
						.subscribe((grant: GrantListingModel) => {
							// const grant: GrantListingModel = {
							// 	id: this.grantId
							// }
							this.criteria.setCriteria({ like: null, grants: [grant], groupIds: null, allVersions: false });

							this.refresh();
							grantLabel = this.route.snapshot.queryParams.grantLabel;
							// this.breadCrumbs = Observable.of([{ parentComponentName: 'GrantEditorComponent', label: grantLabel, url: '/grants/edit/' + this.grantId }]);
							this.criteria.setRefreshCallback((resetPages) => this.refresh(resetPages));
						})

				} else if (params['groupId']) {
					this.itemId = params['groupId'];
					this.showGrant = true;
					const breadCrumbs = [];
					this.allVersions = true;

					this.language.get('NAV-BAR.MY-DMPS').pipe(takeUntil(this._destroyed)).subscribe(x => {
						this.breadCrumbs = observableOf([
							{
								parentComponentName: null,
								label: x,
								url: '/plans'
							}]
						);
					})
					this.criteria.setCriteria(this.getDefaultCriteria());
					this.groupLabel = this.route.snapshot.queryParams.groupLabel;
					this.refresh();
					this.criteria.setRefreshCallback((resetPages) => this.refresh(resetPages));
				} else {
					this.itemId = params['groupId'];
					this.showGrant = true;
					const breadCrumbs = [];

					// if (this.itemId) {
					// 	const dmplabel = this.route.snapshot.queryParams.groupLabel;
					// 	breadCrumbs.push({
					// 		parentComponentName: null,
					// 		label: this.language.instant('NAV-BAR.DMPS'),
					// 		url: '/plans'
					// 	});
					// }
					// else

					this.language.get('NAV-BAR.MY-DMPS').pipe(takeUntil(this._destroyed)).subscribe(x => {
						this.breadCrumbs = observableOf([
							{
								parentComponentName: null,
								label: x,
								url: '/plans'
							}]
						);
					})
					this.criteria.setCriteria(this.getDefaultCriteria());
					this.refresh();
					this.criteria.setRefreshCallback((resetPages) => this.refresh(resetPages));
				}

				if (this.grantId != null) {
					if (grantLabel !== undefined) {
						this.titlePrefix = 'for ' + grantLabel;
					}
				}

			});
	}

	refresh(resetPages = false) {
		if (this._paginator.pageSize === undefined) this._paginator.pageSize = 10;
		if (resetPages) this._paginator.pageIndex = 0;
		const startIndex = this._paginator.pageIndex * this._paginator.pageSize;
		let fields: Array<string> = new Array();
		// if (this.sort && this.sort.active) { fields = this.sort.direction === 'asc' ? ['+' + this.sort.active] : ['-' + this.sort.active]; }
		fields.push('-modified');
		const request = new DataTableRequest<DmpCriteria>(startIndex, this._paginator.pageSize, { fields: fields });
		let value = this.criteria.formGroup.value;
		request.criteria = {
			like: value.like,
			grants: value.grants,
			role: value.role
		}
		if (value.status == 2) {
			request.criteria.isPublic = true;
		} else {
			request.criteria.status = value.status;
			request.criteria.isPublic = false;
		}
		if (value.datasetTemplates)
			request.criteria.datasetTemplates = value.datasetTemplates.map(x => x.id);
		if (value.collaborators)
			request.criteria.collaborators = value.collaborators.map(x => x.id);
		if (value.organisations)
			request.criteria.organisations = value.organisations.map(x => x.id);
		if (this.itemId) {
			request.criteria.groupIds = [this.itemId];
			request.criteria.allVersions = true;
		}
		this.dmpService.getPaged(request, "listing").pipe(takeUntil(this._destroyed)).subscribe(result => {
			if (!result) { return []; }
			if (this._paginator.pageIndex === 0) { this.totalCount = result.totalCount; }
			result.data.map(item => {
				item['datasets'].map(dmp => {
					dmp.url = 'datasets/edit/' + dmp.url;
					dmp.all = 'datasets/dmp/' + item.id;
					return dmp;
				});
				return item;
			});
			this.listingItems = result.data;
		});
	}

	pageThisEvent(event) {
		this.refresh();
	}

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

	addDataset(rowId: String) {
		this.router.navigate(['/datasets/new/' + rowId]);
	}

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

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

	getDefaultCriteria(): DmpCriteria {
		const defaultCriteria = new DmpCriteria();
		return defaultCriteria;
	}

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

// export class DmpDataSource extends DataSource<DmpListingModel> {

// 	totalCount = 0;

// 	constructor(
// 		private _service: DmpService,
// 		private _paginator: MatPaginator,
// 		private _sort: MatSort,
// 		private _criteria: DmpCriteriaComponent,
// 		private itemId
// 	) {
// 		super();
// 	}

// 	connect(): Observable<DmpListingModel[]> {
// 		const displayDataChanges = [
// 			this._paginator.page
// 		];

// 		return Observable.merge(...displayDataChanges)
// 			.startWith(null)
// 			.switchMap(() => {
// 				const startIndex = this._paginator.pageIndex * this._paginator.pageSize;
// 				let fields: Array<string> = new Array();
// 				if (this._sort.active) { fields = this._sort.direction === 'asc' ? ['+' + this._sort.active] : ['-' + this._sort.active]; }
// 				const request = new DataTableRequest<DmpCriteria>(startIndex, this._paginator.pageSize, { fields: fields });
// 				request.criteria = this._criteria.formGroup.value;
// 				if (this.itemId) {
// 					request.criteria.groupIds = [this.itemId];
// 					request.criteria.allVersions = true;
// 				}
// 				return this._service.getPaged(request, "listing");
// 			})
// 			/*.catch((error: any) => {
// 			  this._snackBar.openFromComponent(SnackBarNotificationComponent, {
// 				data: { message: 'GENERAL.SNACK-BAR.FORMS-BAD-REQUEST', language: this._languageService },
// 				duration: 3000,
// 				extraClasses: ['snackbar-warning']
// 			  });
// 			  return Observable.of(null);
// 			})*/
// 			.map(result => {
// 				result.data = result.data;
// 				return result;
// 			})
// 			.map(result => {
// 				return result;
// 			})
// 			.map(result => {
// 				if (!result) { return []; }
// 				if (this._paginator.pageIndex === 0) { this.totalCount = result.totalCount; }
// 				return result.data.map(item => {
// 					item['datasets'].map(dmp => {
// 						dmp.url = 'datasets/edit/' + dmp.url;
// 						dmp.all = 'datasets/dmp/' + item.id;
// 						return dmp;
// 					});
// 					return item;
// 				});
// 			});
// 	}

// 	disconnect() {
// 	}
// }
