
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 { DatasetStatus } from '@app/core/common/enum/dataset-status';
import { DataTableRequest } from '@app/core/model/data-table/data-table-request';
import { DatasetListingModel } from '@app/core/model/dataset/dataset-listing';
import { DatasetCriteria } from '@app/core/query/dataset/dataset-criteria';
import { DatasetService } from '@app/core/services/dataset/dataset.service';
import { DmpService } from '@app/core/services/dmp/dmp.service';
import { DatasetCriteriaComponent } from '@app/ui/dataset/listing/criteria/dataset-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';

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

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

	breadCrumbs: Observable<BreadcrumbItem[]>;

	titlePrefix: String;
	dmpId: string;
	status: Number;
	totalCount: number;
	dmpSearchEnabled = true;
	listingItems: DatasetListingModel[] = [];

	constructor(
		private datasetService: DatasetService,
		private router: Router,
		private route: ActivatedRoute,
		private dmpService: DmpService,
		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'];
				this.status = queryParams['status'];
				// Makes multiple post requests
				// this.criteria.setRefreshCallback(() => this.refresh());
				if (this.dmpId != null) {
					this.dmpSearchEnabled = false;
					const dmp = await this.dmpService.getSingle(this.dmpId).toPromise();
					this.criteria.setCriteria(this.getDefaultCriteria(dmp));
					this.refresh();
					this.criteria.setRefreshCallback((resetPages) => this.refresh(resetPages));
					this.breadCrumbs = observableOf([{
						parentComponentName: 'DmpEditorComponent',
						label: dmp.label,
						url: '/plans/edit/' + this.dmpId
					}]);
					if (params['dmpLabel'] !== undefined) {
						this.titlePrefix = 'for ' + params['dmpLabel'];
					}
				} else {
					this.criteria.setCriteria(this.getDefaultCriteria());
					this.refresh();
					this.criteria.setRefreshCallback((resetPages) => this.refresh(resetPages));
					this.breadCrumbs = observableOf([{
						parentComponentName: null,
						label: this.language.instant('NAV-BAR.MY-DATASET-DESCRIPTIONS'),
						url: "/datasets"
					}]);
				}

				if (this.status != null && this.status == DatasetStatus.Draft) {
					this.criteria.setCriteria(this.getDraftCriteria());
					this.criteria.setRefreshCallback((resetPages) => this.refresh(resetPages));
					this.refresh();
				}
			});
	}

	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();
		fields.push('-modified');
		//if (this.sort && this.sort.active) { fields = this.sort.direction === 'asc' ? ['+' + this.sort.active] : ['-' + this.sort.active]; }
		const request = new DataTableRequest<DatasetCriteria>(startIndex, this._paginator.pageSize, { fields: fields });
		let value = this.criteria.formGroup.value;
		request.criteria = {
			like: value.like,
			status: value.status,
			allVersions: value.allVersions,
			role: value.role
		}
		if (value.tags) {
			request.criteria.tags = value.tags.map(x => x.id);
		}
		if (value.collaborators) {
			request.criteria.collaborators = value.collaborators.map(x => x.id);
		}
		if (value.dmpIds) {
			request.criteria.dmpIds = value.dmpIds.map(x => x.id);
		}
		if (value.groupIds) {
			request.criteria.groupIds = value.groupIds.map(x => x.groupId);
		}
		if (value.grants) {
			request.criteria.grants = value.grants.map(x => x.id);
		}
		if (value.organisations) {
			request.criteria.organisations = value.organisations.map(x => x.id);
		}
		if (value.datasetTemplates) {
			request.criteria.datasetTemplates = value.datasetTemplates.map(x => x.id)
		}
		// if (this.itemId) {
		// 	// request.criteria.groupIds = [this.itemId];
		// 	request.criteria.allVersions = true;
		// }
		this.datasetService.getPaged(request).pipe(takeUntil(this._destroyed)).subscribe(result => {
			if (!result) { return []; }
			if (this._paginator.pageIndex === 0) { this.totalCount = result.totalCount; }
			this.listingItems = result.data;
		});
	}

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


	getDefaultCriteria(dmp: any = null): DatasetCriteria {
		const defaultCriteria = new DatasetCriteria();
		if (dmp != null) {
			defaultCriteria.dmpIds.push(dmp);
		}
		return defaultCriteria;
	}

	getDraftCriteria(): DatasetCriteria {
		const draftCriteria = new DatasetCriteria();
		draftCriteria.status = DatasetStatus.Draft;
		return draftCriteria;
	}

	makeItPublic(id: String) {
		this.datasetService.makeDatasetPublic(id)
			.pipe(takeUntil(this._destroyed))
			.subscribe();
	}

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