
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { AppRole } from '@app/core/common/enum/app-role';
import { SearchBarItem } from '@app/core/model/dashboard/search-bar-item';
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 { GrantService } from '@app/core/services/grant/grant.service';
import { ProgressIndicationService } from '@app/core/services/progress-indication/progress-indication-service';
import { SearchBarService } from '@app/core/services/search-bar/search-bar.service';
import { SingleAutoCompleteConfiguration } from '@app/library/auto-complete/single/single-auto-complete-configuration';
import { UserDialogComponent } from '@app/ui/misc/navigation/user-dialog/user-dialog.component';
import { BaseComponent } from '@common/base/base.component';
import { Observable } from 'rxjs';
import { debounceTime, distinctUntilChanged, mergeMap, takeUntil } from 'rxjs/operators';

export enum SearchBarType {
	Dataset = 0,
	Dmp = 1,
	Grant = 2
}

@Component({
	selector: 'app-navigation',
	templateUrl: 'navigation.component.html',
	styleUrls: ['./navigation.component.scss']
})
export class NavigationComponent extends BaseComponent implements OnInit {
	progressIndication = false;
	public search = false;
	grantAutoCompleteConfiguration: SingleAutoCompleteConfiguration;
	public searchControl = new FormControl();
	filteredOptions: Observable<SearchBarItem[]>;

	events: string[] = [];
	opened: boolean;
	constructor(
		private authentication: AuthService,
		private dialog: MatDialog,
		private grantService: GrantService,
		private searchBarService: SearchBarService,
		private router: Router,
		private progressIndicationService: ProgressIndicationService
	) {
		super();
	}

	ngOnInit() {
		this.progressIndicationService.getProgressIndicationObservable().pipe(takeUntil(this._destroyed)).subscribe(x => {
			setTimeout(() => { this.progressIndication = x; });
		});

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

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

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

	public logout(): void {
		this.authentication.logout();
	}

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

	public isAdmin(): boolean {
		if (!this.authentication.current()) { return false; }
		const principalRoles = this.authentication.current().authorities;
		for (let i = 0; i < principalRoles.length; i++) {
			if (principalRoles[i] === AppRole.Admin) {
				return true;
			}
		}
		return false;
	}

	public principalHasAvatar(): boolean {
		return this.authentication.current().avatarUrl != null && this.authentication.current().avatarUrl.length > 0;
	}

	public getPrincipalAvatar(): string {
		return this.authentication.current().avatarUrl;
	}

	public getDefaultAvatar(): string {
		return 'assets/images/profile-placeholder.png';
	}

	openProfile() {
		const dialogRef = this.dialog.open(UserDialogComponent, {
			hasBackdrop: true,
			autoFocus: false,
			closeOnNavigation: true,
			disableClose: false,
			position: { top: '64px', right: '1em' },
			panelClass: 'custom-userbox'
		});
	}

	onOptionSelected(event: any) {
		this.search = false;
		this.searchControl.patchValue(null);
		const selectedSearchBarItem = event.option.value;
		if (selectedSearchBarItem.type === SearchBarType.Dataset) { this.router.navigate(['datasets/edit/' + selectedSearchBarItem.id]); }
		if (selectedSearchBarItem.type === SearchBarType.Grant) { this.router.navigate(['grants/edit/' + selectedSearchBarItem.id]); }
		if (selectedSearchBarItem.type === SearchBarType.Dmp) { this.router.navigate(['plans/edit/' + selectedSearchBarItem.id]); }
	}

	transformType(type) {
		switch (type) {
			case SearchBarType.Dataset: return 'Dataset';
			case SearchBarType.Dmp: return 'DMP';
			case SearchBarType.Grant: return 'Grant';
		}
	}
}
