
import { Component, OnInit, ViewChild } from "@angular/core";
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 { ExploreDmpCriteriaModel } from '@app/core/query/explore-dmp/explore-dmp-criteria';
import { DmpService } from '@app/core/services/dmp/dmp.service';
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';

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

	@ViewChild(MatPaginator, { static: true }) _paginator: MatPaginator;
	sort = new MatSort();

	exploreDmpCriteriaModel: ExploreDmpCriteriaModel = new ExploreDmpCriteriaModel();
	titlePrefix: string;
	totalCount: number;
	listingItems: DmpListingModel[] = [];
	breadCrumbs: Observable<BreadcrumbItem[]>;
	linkToDmpId: string;
	groupId: string;
	allVersions: boolean = false;
	groupLabel: string;

	constructor(
		private dmpService: DmpService,
		private router: Router,
		private route: ActivatedRoute,
		private language: TranslateService,
	) {
		super();
		this.sort.direction = 'desc';
		this.sort.active = "publishedAt";
	}

	ngOnInit() {
		this.route.params
			.pipe(takeUntil(this._destroyed))
			.subscribe(params => {
				if (params['groupId']) {
					this.groupId = params['groupId'];
					this.exploreDmpCriteriaModel.groupIds.push(this.groupId);
					this.exploreDmpCriteriaModel.allVersions = true;
					this.allVersions = true;
					this.route.queryParams
						.pipe(takeUntil(this._destroyed))
						.subscribe(queryParams => {
							if (queryParams["groupLabel"]) {
								this.groupLabel = queryParams["groupLabel"];
							}
						})
				}

				this.refresh();
				const breadCrumbs = [];
				breadCrumbs.push({
					parentComponentName: null,
					label: this.language.instant('NAV-BAR.PUBLIC-DMPS'),
					url: "/explore-plans"
				})
				this.breadCrumbs = observableOf(breadCrumbs);
			})
	}

	refresh() {
		if (this._paginator.pageSize === undefined) this._paginator.pageSize = 10;
		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]; }
		const request = new DataTableRequest<ExploreDmpCriteriaModel>(startIndex, this._paginator.pageSize, { fields: fields });
		request.criteria = this.exploreDmpCriteriaModel || this.getDefaultCriteria();
		this.dmpService.getPublicPaged(request, "listing").pipe(takeUntil(this._destroyed)).subscribe(result => {
			if (!result) { return []; }
			if (this._paginator.pageIndex === 0) { this.totalCount = result.totalCount; }
			this.listingItems = result.data;
		});
	}


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

	onCriteriaChange(event: ExploreDmpCriteriaModel) {
		this.exploreDmpCriteriaModel = event;
		if (this.allVersions == true) this.exploreDmpCriteriaModel.allVersions = this.allVersions;
		if (this.groupId) this.exploreDmpCriteriaModel.groupIds.push(this.groupId);
		this._paginator.pageIndex = 0;
		this.refresh();
	}

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

	// rowClicked(dmp: DmpListingModel) {
	// 	this.router.navigate(['overview', dmp.id], { relativeTo: this.route });
	// }

	// @ViewChild(MatPaginator) _paginator: MatPaginator;
	// @ViewChild(MatSort) sort: MatSort;
	// criteria: ExploreDmpCriteriaModel = new ExploreDmpCriteriaModel();

	// dataSource: DmpDataSource | null;
	// displayedColumns: String[] = ['name', 'grant', 'organisations', 'created'];
	// pageEvent: PageEvent;
	// titlePrefix: String;
	// dmpId: string;

	// constructor(
	// 	public dmpService: DmpService,
	// 	private router: Router,
	// 	private languageService: TranslateService,
	// 	public snackBar: MatSnackBar,
	// 	public route: ActivatedRoute
	// ) {
	// 	super();
	// }

	// ngOnInit() {
	// 	this.refresh();
	// }

	// rowClick(rowId: String) {
	// 	this.router.navigate(['/plans/publicEdit/' + rowId]);
	// }

	// refresh() {
	// 	this.dataSource = new DmpDataSource(this.dmpService, this._paginator, this.sort, this.languageService, this.snackBar, this.criteria);
	// }

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

	// onCriteriaChange(event: ExploreDmpCriteriaModel) {
	// 	//console.log(event)
	// 	this.criteria = event;
	// 	this.refresh();
	// }
}

// export class DmpDataSource extends DataSource<DmpListingModel> {

// 	totalCount = 0;

// 	constructor(
// 		private _service: DmpService,
// 		private _paginator: MatPaginator,
// 		private _sort: MatSort,
// 		private _languageService: TranslateService,
// 		private _snackBar: MatSnackBar,
// 		private _criteria: ExploreDmpCriteriaModel,
// 	) {
// 		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<ExploreDmpCriteriaModel>(startIndex, this._paginator.pageSize, { fields: fields });
// 				request.criteria = this._criteria;
// 				//if (this.dmpId) request.criteria.allVersions = true;
// 				return this._service.getPublicPaged(request);
// 			})
// 			.map(result => {
// 				if (!result) { return []; }
// 				if (this._paginator.pageIndex === 0) { this.totalCount = result.totalCount; }
// 				return result.data;
// 			});
// 	}

// 	disconnect(): void {
// 		// No-op
// 	}
// }
