import { Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { TranslateService } from '@ngx-translate/core';
import { AuthService } from '../../core/services/auth/auth.service';
import { UserDialogComponent } from '../misc/navigation/user-dialog/user-dialog.component';
import { Principal } from '../../core/model/auth/principal';
import { AppRole } from '../../core/common/enum/app-role';
import { Router } from '@angular/router';
import { Location } from '@angular/common';
import { LanguageDialogComponent } from '../language/dialog/language-dialog.component';
import { MatomoService } from '@app/core/services/matomo/matomo-service';
import { HttpClient } from '@angular/common/http';

declare interface RouteInfo {
	path: string;
	title: string;
	icon: string;
	url?: string;
}
declare interface GroupMenuItem {
	title: string;
	routes: RouteInfo[];
	requiresAuthentication: boolean;
	requiresSpecialPermission?: AppRole;
	requiresAdmin: boolean;
	isGeneral: boolean;
}

export const GENERAL_ROUTES: RouteInfo[] = [
	{ path: '/home', title: 'SIDE-BAR.DASHBOARD', icon: 'home' }
];
export const DMP_ROUTES: RouteInfo[] = [
	{ path: '/plans', title: 'SIDE-BAR.MY-DMPS', icon: 'library_books' },
	{ path: '/datasets', title: 'SIDE-BAR.MY-DATASETS', icon: 'dns' },
	// { path: '/quick-wizard', title: 'SIDE-BAR.QUICK-WIZARD', icon: 'play_circle_outline' },
	// { path: '/plans/new', title: 'SIDE-BAR.ADD-EXPERT', icon: 'playlist_add' }
];
export const DATASETS_ROUTES: RouteInfo[] = [
	{ path: '/explore-plans', title: 'SIDE-BAR.PUBLIC-DMPS', icon: 'library_books' },
	{ path: '/explore', title: 'SIDE-BAR.PUBLIC-DESC', icon: 'dns' },
	// { path: '/datasetcreatewizard', title: 'SIDE-BAR.QUICK-WIZARD-DATASET', icon: "play_circle_outline" },
];

export const PUBLIC_ROUTES: RouteInfo[] = [
	{ path: '/explore-plans', title: 'SIDE-BAR.PUBLIC-DMPS', icon: 'library_books' },
	{ path: '/explore', title: 'SIDE-BAR.PUBLIC-DESC', icon: 'dns' }
];

// export const GRANTS_ROUTES: RouteInfo[] = [
// 	{ path: '/grants', title: 'SIDE-BAR.MY-GRANTS', icon: 'work_outline' }
// ];

export const ADMIN_ROUTES: RouteInfo[] = [
	{ path: '/dmp-profiles', title: 'SIDE-BAR.DMP-TEMPLATES', icon: 'library_books' },
	{ path: '/dataset-profiles', title: 'SIDE-BAR.DATASET-TEMPLATES', icon: 'library_books' },
	{ path: '/users', title: 'SIDE-BAR.USERS', icon: 'people' },
	{ path: '/language-editor', title: 'SIDE-BAR.LANGUAGE-EDITOR', icon: 'language' },
	{ path: '/user-guide-editor', title: 'SIDE-BAR.GUIDE-EDITOR', icon: 'import_contacts' }
];

export const DATASET_TEMPLATE_ROUTES: RouteInfo[] = [
	{ path: '/dataset-profiles', title: 'SIDE-BAR.DATASET-TEMPLATES', icon: 'library_books' }
];

export const INFO_ROUTES: RouteInfo[] = [
	{ path: '/co-branding', title: 'SIDE-BAR.CO-BRANDING', icon: 'toll' },
	{ path: '/contact-support', title: 'SIDE-BAR.SUPPORT', icon: 'help' },
	{ path: '/feedback', title: 'SIDE-BAR.FEEDBACK', icon: 'feedback', url: 'https://docs.google.com/forms/d/12RSCrUjdSDp2LZLpjDKOi44cN1fLDD2q1-F66SqZIis/viewform?edit_requested=true' }
];

// export const HISTORY_ROUTES: RouteInfo[] = [
//   { path: '/typography', title: 'SIDE-BAR.HISTORY-VISITED',  icon: 'visibility'},
//   { path: '/icons', title: 'SIDE-BAR.HISTORY-EDITED',  icon: 'edit'}
// ];

@Component({
	selector: 'app-sidebar',
	templateUrl: './sidebar.component.html',
	styleUrls: ['./sidebar.component.css', './sidebar.component.scss']
})
export class SidebarComponent implements OnInit {
	generalItems: GroupMenuItem;
	dmpItems: GroupMenuItem;
	adminItems: GroupMenuItem;
	datasetTemplateItems: GroupMenuItem;
	//   historyItems: GroupMenuItem;
	datasetItems: GroupMenuItem;
	grantItems: GroupMenuItem;
	publicItems: GroupMenuItem;
	infoItems: GroupMenuItem;
	groupMenuItems: GroupMenuItem[] = [];
	private toggleButton: any;
	currentRoute: string;

	constructor(
		public translate: TranslateService,
		private authentication: AuthService,
		private dialog: MatDialog,
		public router: Router,
		private location: Location,
		private httpClient: HttpClient,
		private matomoService: MatomoService
		) {
	}

	ngOnInit() {
		this.matomoService.trackPageView('Sidebar');
		this.currentRoute = this.router.url;
		this.generalItems = {
			title: 'SIDE-BAR.GENERAL',
			routes: GENERAL_ROUTES,
			requiresAuthentication: false,
			requiresAdmin: false,
			isGeneral: true
		}
		this.groupMenuItems.push(this.generalItems);

		this.dmpItems = {
			title: 'SIDE-BAR.DMP',
			routes: DMP_ROUTES,
			requiresAuthentication: true,
			requiresAdmin: false,
			isGeneral: false
		}
		this.groupMenuItems.push(this.dmpItems);

		this.datasetItems = {
			title: 'SIDE-BAR.DATASETS',
			routes: DATASETS_ROUTES,
			requiresAuthentication: true,
			requiresAdmin: false,
			isGeneral: false
		}
		this.groupMenuItems.push(this.datasetItems);

		// ----------- UNCOMMENT TO ADD AGAIN GRANTS --------
		// this.grantItems = {
		// 	title: 'SIDE-BAR.GRANTS',
		// 	routes: GRANTS_ROUTES,
		// 	requiresAuthentication: true,
		// 	requiresAdmin: false,
		// 	isGeneral: false
		// }
		// this.groupMenuItems.push(this.grantItems);

		this.adminItems = {
			title: 'SIDE-BAR.ADMIN',
			routes: ADMIN_ROUTES,
			requiresAuthentication: true,
			requiresAdmin: true,
			isGeneral: false
		}
		this.groupMenuItems.push(this.adminItems);

		this.datasetTemplateItems = {
			title: 'SIDE-BAR.ADMIN',
			routes: DATASET_TEMPLATE_ROUTES,
			requiresAuthentication: true,
			requiresSpecialPermission: AppRole.DatasetTemplateEditor,
			requiresAdmin: false,
			isGeneral: false
		}
		this.groupMenuItems.push(this.datasetTemplateItems);

		this.publicItems = {
			title: 'SIDE-BAR.PUBLIC',
			routes: PUBLIC_ROUTES,
			requiresAuthentication: false,
			requiresAdmin: false,
			isGeneral: false
		}
		this.groupMenuItems.push(this.publicItems);

		this.infoItems = {
			title: "",
			routes: INFO_ROUTES,
			requiresAuthentication: false,
			requiresAdmin: false,
			isGeneral: false
		}
		this.groupMenuItems.push(this.infoItems);

		this.router.events.subscribe((event) => this.currentRoute = this.router.url);

		// this.historyItems = {
		// 	title: 'SIDE-BAR.HISTORY',
		// 	routes: HISTORY_ROUTES
		// }
		// this.groupMenuItems.push(this.historyItems);
	}

	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';
	}

	public applyFallbackAvatar(ev: Event) {
		(ev.target as HTMLImageElement).src = this.getDefaultAvatar();
	}

	public isAuthenticated(): boolean {
		const myBollean = this.isAdmin();
		return !(!this.authentication.current());
	}

	public isAdmin(): boolean {
		const principal: Principal = this.authentication.current();
		if (principal) {
			if (principal.authorities.find(role => role === AppRole.Admin)) {
				return true;
			}
			else {
				return false;
			}
		} else {
			return false;
		}
	}

	public hasPermission(permission: AppRole): boolean {
		const principal: Principal = this.authentication.current();
		if (principal) {
			if (principal.authorities.find(role => role === permission)) {
				return true;
			}
			else {
				return false;
			}
		} else {
			return false;
		}
	}

	isLoginRouteActivated(): boolean {
		return this.location.path().indexOf('/login') > -1;
	}

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

	showItem(value: GroupMenuItem) {
		if (this.isAuthenticated()) {
			if (value.requiresAdmin) {
				return this.isAdmin();
			}
			else if (value.requiresSpecialPermission !== undefined) {
				return this.hasPermission(value.requiresSpecialPermission);
			}
			else {
				return value.isGeneral || value.requiresAuthentication;
			}
		}
		else {
			return !value.requiresAuthentication;
		}
	}

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

	public onInvalidUrl(): boolean {
		return this.currentRoute === '/language-editor' || this.currentRoute === '/profile';
	}

	public openLanguageDialog() {
		if (this.dialog.openDialogs.length > 0) {
			this.dialog.closeAll();
		}
		else {
			const dialogRef = this.dialog.open(LanguageDialogComponent, {
				disableClose: true,
				data: {
					isDialog: true
				}
			});
		}
	}

	public openFeedback(groupMenuRoute: RouteInfo) {
		window.open(groupMenuRoute.url, '_blank');
	}

}
