import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router, RouterLink, RouterLinkActive } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { MatToolbarModule } from '@angular/material/toolbar';
import { Observable, Subscription } from 'rxjs';

import { User } from 'src/app/core/models';
import { UserService } from 'src/app/core/services';

@Component({
    selector: 'huapp-layout-header',
    templateUrl: './header.component.html',
    standalone: true,
    imports: [
        CommonModule, RouterLink, RouterLinkActive, 
        MatToolbarModule, MatButtonModule, MatMenuModule, MatIconModule
    ]
})
export class HeaderComponent implements OnInit, OnDestroy {

    private _currentUser: Subscription = new Subscription();
    private _isAuthenticated: Subscription = new Subscription();
    private isAuthenticated = false;
    currentUser: User = {} as User;

    constructor(
        private router: Router,
        private userService: UserService
    ) { }

    acLogo = '/assets/images/logo-aucoffre_fr.svg';

    ngOnInit() {
        const user$: Observable<User> = this.userService.currentUser;
        this._currentUser = user$.subscribe(
            (userData) => {
                this.currentUser = userData;
            }
        );
        const auth$: Observable<boolean> = this.userService.isAuthenticated;
        this._isAuthenticated = auth$.subscribe(
            (value) => {
                this.isAuthenticated = value;
            }
        );
    }

    ngOnDestroy() {
        this._currentUser.unsubscribe();
        this._isAuthenticated.unsubscribe();
    }

    goToGitHub() {
        window.open('https://github.com/rampeur', '_blank');
    }

    isLogged(): boolean {
        return this.isAuthenticated;
    }

    logout() {
        this.userService.purgeAuth();
        this.router.navigateByUrl('/');
    }
}
