
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { RecentActivityType } from '@app/core/common/enum/recent-activity-type';
import { DashboardStatisticsModel } from '@app/core/model/dashboard/dashboard-statistics-model';
import { SearchBarItem } from '@app/core/model/dashboard/search-bar-item';
import { DataTableRequest } from '@app/core/model/data-table/data-table-request';
import { DatasetListingModel } from '@app/core/model/dataset/dataset-listing';
import { DmpListingModel } from '@app/core/model/dmp/dmp-listing';
import { ExploreDatasetCriteriaModel } from '@app/core/query/explore-dataset/explore-dataset-criteria';
import { ExploreDmpCriteriaModel } from '@app/core/query/explore-dmp/explore-dmp-criteria';
import { GrantCriteria } from '@app/core/query/grant/grant-criteria';
import { RequestItem } from '@app/core/query/request-item';
import { AuthService } from '@app/core/services/auth/auth.service';
import { DashboardService } from '@app/core/services/dashboard/dashboard.service';
import { DatasetService } from '@app/core/services/dataset/dataset.service';
import { DmpService } from '@app/core/services/dmp/dmp.service';
import { GrantService } from '@app/core/services/grant/grant.service';
import { SearchBarService } from '@app/core/services/search-bar/search-bar.service';
import { UserService } from '@app/core/services/user/user.service';
import { SingleAutoCompleteConfiguration } from '@app/library/auto-complete/single/single-auto-complete-configuration';
import { BaseComponent } from '@common/base/base.component';
import { Observable, of as observableOf } from 'rxjs';
import { mergeMap, takeUntil } from 'rxjs/operators';
import { BreadcrumbItem } from '../misc/breadcrumb/definition/breadcrumb-item';
import { IBreadCrumbComponent } from '../misc/breadcrumb/definition/IBreadCrumbComponent';


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

	breadCrumbs: Observable<BreadcrumbItem[]>;

	public userInfo: any;
	datasetActivities: any[];
	grantActivities: any[];
	dmpActivities: any[];
	organisationActivities: any[];
	public dashboardStatisticsData: DashboardStatisticsModel;
	public formControl = new FormControl();
	grantAutoCompleteConfiguration: SingleAutoCompleteConfiguration;
	public searchControl = new FormControl();
	filteredOptions: Observable<SearchBarItem[]>;
	recentActivityTypeEnum = RecentActivityType;
	public search = false;
	dmpListingItems: DmpListingModel[] = [];
	datasetListingItems: DatasetListingModel[] = [];

	constructor(
		private router: Router,
		private route: ActivatedRoute,
		private grantService: GrantService,
		private dmpService: DmpService,
		private datasetService: DatasetService,
		private dashboardService: DashboardService,
		private searchBarService: SearchBarService,
		private authentication: AuthService,
		private userService: UserService

	) {
		super();
		// this.dashboardStatisticsData.totalDataManagementPlanCount = 0;
		// this.dashboardStatisticsData.totalDataSetCount = 0;
		// this.dashboardStatisticsData.totalGrantCount = 0;
	}


	ngOnInit() {

		// if (this.isAuthenticated()) {
		// 	this.userService.getRecentActivity()
		// 		.pipe(takeUntil(this._destroyed))
		// 		.subscribe(response => {
		// 			this.datasetActivities = response['recentDatasetActivities'];
		// 			this.dmpActivities = response['recentDmpActivities'];
		// 			this.grantActivities = response['recentGrantActivities'];
		// 			this.organisationActivities = response['totalOrganisationCount'];
		// 		});
		// }

		// this.grantAutoCompleteConfiguration = {
		// 	filterFn: this.searchGrant.bind(this),
		// 	items: this.searchGrant(''),
		// 	displayFn: (item) => item['label'],
		// 	titleFn: (item) => item['label']
		// };

		const breadCrumbs = [];
		this.breadCrumbs = observableOf(breadCrumbs);

		if (!this.isAuthenticated()) {
			this.dashboardService.getStatistics()
				.pipe(takeUntil(this._destroyed))
				.subscribe(results => {
					//let data = results['payload'];
					this.dashboardStatisticsData = results;
				});
			this.getPublicDmps();
			this.getPublicDatasets();
		} else {
			this.dashboardService.getUserStatistics()
				.pipe(takeUntil(this._destroyed))
				.subscribe(results => {
					this.dashboardStatisticsData = results;
				});
		}

		this.filteredOptions = this.searchControl.valueChanges.pipe(mergeMap(x => {
			return this.searchBarService.search(x);
		}));
	}

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

	searchGrant(query: string) {
		const grantRequestItem: RequestItem<GrantCriteria> = new RequestItem();
		grantRequestItem.criteria = new GrantCriteria();
		grantRequestItem.criteria.like = query;
		return this.grantService.getWithExternal(grantRequestItem);
	}

	redirect(id: string, type: RecentActivityType) {
		switch (type) {
			case RecentActivityType.Grant: {
				this.router.navigate(['grants/edit/' + id]);
				return;
			}
			case RecentActivityType.Dataset: {
				this.router.navigate(['datasets/edit/' + id]);
				return;
			}
			case RecentActivityType.Dmp: {
				this.router.navigate(['plans/edit/' + id]);
				return;
			}
			default: throw new Error('Unsupported Activity Type ');
		}
	}

	getPublicDmps() {
		const dmpCriteria = new ExploreDmpCriteriaModel();
		const fields: Array<string> = new Array<string>();
		fields.push('-finalizedAt');
		const dataTableRequest: DataTableRequest<ExploreDmpCriteriaModel> = new DataTableRequest(0, 2, { fields: fields });
		dataTableRequest.criteria = dmpCriteria;
		return this.dmpService.getPublicPaged(dataTableRequest, "listing").pipe(takeUntil(this._destroyed)).subscribe(result => { this.dmpListingItems = result.data; });
	}

	getPublicDatasets() {
		const dmpCriteria = new ExploreDatasetCriteriaModel();
		const fields: Array<string> = new Array<string>();
		fields.push('-modified');
		const dataTableRequest: DataTableRequest<ExploreDatasetCriteriaModel> = new DataTableRequest(0, 4, { fields: fields });
		dataTableRequest.criteria = dmpCriteria;
		return this.datasetService.getPublicPaged(dataTableRequest).pipe(takeUntil(this._destroyed)).subscribe(result => { this.datasetListingItems = result.data; });
	}

	dmpClicked(dmp: DmpListingModel) {
		if (!this.isAuthenticated()) {
			this.router.navigate(['../explore-plans/overview', dmp.id], { relativeTo: this.route });
		} else {
			this.router.navigate(['/plans/publicEdit/' + dmp.id]);
		}
	}

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

	// viewAllPublicDmpsClicked() {
	// 	this.router.navigate(['/explore-plans']);
	// }

	// viewAllPublicDatasetsClicked() {
	// 	this.router.navigate(['explore']);
	// }
}
