import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { DataTableRequest } from '@app/core/model/data-table/data-table-request';
import { DatasetListingModel } from '@app/core/model/dataset/dataset-listing';
import { ExploreDatasetCriteriaModel } from '@app/core/query/explore-dataset/explore-dataset-criteria';
import { DatasetService } from '@app/core/services/dataset/dataset.service';
import { DmpService } from '@app/core/services/dmp/dmp.service';
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 { BreadcrumbItem } from '../misc/breadcrumb/definition/breadcrumb-item';
import { IBreadCrumbComponent } from '../misc/breadcrumb/definition/IBreadCrumbComponent';


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

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

	totalCount: number;
	listingItems: DatasetListingModel[] = [];
	exploreDatasetCriteriaModel: ExploreDatasetCriteriaModel;
	breadCrumbs: Observable<BreadcrumbItem[]>;
	dmpId: string;
	dmpSearchEnabled = true;
	titlePrefix: String;

	constructor(
		private datasetService: DatasetService,
		private dmpService: DmpService,
		private router: Router,
		private route: ActivatedRoute,
		private language: TranslateService,
	) {
		super();
	}

	ngOnInit() {
		this.route.params
			.pipe(takeUntil(this._destroyed))
			.subscribe(async (params: Params) => {
				const queryParams = this.route.snapshot.queryParams;
				this.dmpId = queryParams['dmpId'];
				if (this.dmpId != null) {
					this.dmpSearchEnabled = false;
					const dmp = await this.dmpService.getSinglePublic(this.dmpId).toPromise();

					const fields: Array<string> = [];
					const dmpDataTableRequest: DataTableRequest<ExploreDatasetCriteriaModel> = new DataTableRequest(0, this._paginator.pageSize, { fields: fields });
					dmpDataTableRequest.criteria = new ExploreDatasetCriteriaModel();
					dmpDataTableRequest.criteria.dmpIds.push(this.dmpId);

					this.datasetService.getPublicPaged(dmpDataTableRequest).pipe(takeUntil(this._destroyed)).subscribe(result => {
						if (!result) { return []; }
						if (this._paginator.pageIndex === 0) { this.totalCount = result.totalCount; }
						this.listingItems = result.data;
					});


				} else {
					this.refresh();
				}
			});

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

	refresh(resetPages = false) {
		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<ExploreDatasetCriteriaModel>(startIndex, this._paginator.pageSize, { fields: fields });
		request.criteria = this.exploreDatasetCriteriaModel || this.getDefaultCriteria();
		this.datasetService.getPublicPaged(request).pipe(takeUntil(this._destroyed)).subscribe(result => {
			if (!result) { return []; }
			if (this._paginator.pageIndex === 0) { this.totalCount = result.totalCount; }
			this.listingItems = result.data;
		});
	}

	// rowClicked(dataset: DatasetListingModel) {
	// 	this.router.navigate(['/datasets/publicEdit/' + dataset.id]);
	// }

	onCriteriaChange(event: ExploreDatasetCriteriaModel) {
		this.exploreDatasetCriteriaModel = event;
		this._paginator.pageIndex = 0;
		this.refresh();
	}

	getDefaultCriteria(): ExploreDatasetCriteriaModel {
		const defaultCriteria = new ExploreDatasetCriteriaModel();
		// if (dmp != null) {
		// 	defaultCriteria.dmpIds.push(dmp.id);
		// }
		return defaultCriteria;
	}

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