import { Component, inject } from '@angular/core';
import { Router, RouterModule } from '@angular/router';
import { UserService } from 'src/app/core/user/user.service';
import { AuthService } from '../auth.service';
import { CommonModule } from '@angular/common';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatButtonModule } from '@angular/material/button';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
  standalone: true,
  imports: [ 
    CommonModule,
    MatToolbarModule,
    RouterModule,
    MatButtonModule
  ]
})
export class HomeComponent {
  private authService: AuthService = inject(AuthService);
  private userService: UserService = inject(UserService);
  private router: Router = inject(Router);
  

  constructor(
   ) {}

  
  ngOnInit(): void {    
    this.loginFromLocalStorage();
    
  }

  get username(): string {
    if (!this.authService || !this.authService.isLoggedIn()) { return ''}
    return this.authService.user.firstName + ' ' + this.authService.user.lastName
  }

  logout() {
    this.authService.logout();
  }

  get isLoggedIn(): boolean {
    return this.authService.isLoggedIn()
  }

  private async loginFromLocalStorage() {
    const success = await this.authService.loginFromLocalStorage();

    if (!success) { 
      this.router.navigate(['/auth']).then();
      return; 
    }

    if (this.authService && this.authService.isLoggedIn()) {
      this.userService.loadTeamsOfUser();
    }

    if (this.router.url == '/') {
      this.router.navigate(['/dashboard']).then();
    }
  }

  async login() {


    // this.router.navigate(['/auth']).then();

  }

}
