import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../core/services/auth.service';
import { Category } from '../core/entities';
import { HeaderService } from './header.service';
import { environment } from '../../environments/environment';

const SIDENAV_WIDTH = '300px';

@Component({
	selector: 'app-header',
	templateUrl: './header.component.html',
	styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
	isAdmin: boolean;
	listCategories: Array<Category> = [];
	title: string;
	accordionOpenned: Array<Boolean> = [];

	constructor(
		private authService: AuthService,
		private headerService: HeaderService,
		private router: Router
	) {}

	ngOnInit() {
		this.title = environment.title;
		this.isAdmin = this.authService.isAdmin();
		this.headerService.getAllCategories().subscribe(listCategories => {
			this.listCategories = listCategories;
		});
	}

	isAuthenticated(): boolean {
		// console.log('Checking if user is connected... for header');
		return this.authService.isAuthenticated();
	}

	openSidebar(): void {
		document.getElementById('sidenav').style.width = SIDENAV_WIDTH;
		document.getElementById('overlay').style.display = 'block';
	}

	closeSidebar(): void {
		document.getElementById('sidenav').style.width = '0';
		document.getElementById('overlay').style.display = 'none';
	}

	/**
	 * Redirect the user to the page to show the posts of the category which its id is in parameters.
	 *
	 * @param categoryId The id of the category which we need to show its posts after redirection.
	 */
	openPostsByCategory(categoryId: string): void {
		this.closeSidebar();

		this.router.routeReuseStrategy.shouldReuseRoute = () => false;
		this.router.navigateByUrl('/posts/byCategory/' + categoryId).then(() => {
			this.router.navigated = false;
			this.router.navigate([this.router.url]);
		});
	}

	/**
	 * Opens the accordion which correspond to the category in parameters.
	 *
	 * @param category The category which its accodion needs to be open.
	 */
	openCategoriesLinks(category: Category): void {
		const divCategoriesLinks = document.getElementById('category-' + category.id);

		divCategoriesLinks.classList.toggle('active');
		const divContent = divCategoriesLinks.nextElementSibling as HTMLElement;
		if (divContent.style.maxHeight) {
			divContent.style.maxHeight = null;
			this.accordionOpenned[category.id] = false;
		} else {
			divContent.style.maxHeight = divContent.scrollHeight + 'px';
			this.accordionOpenned[category.id] = true;
		}
	}
}
