import { Component, inject } from '@angular/core';
import { AuthService } from '../auth.service';
import { Router, RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { MatCardModule } from '@angular/material/card';
import { AuthGuard } from '../../core/guards/auth.guard';
import { MatButtonModule } from '@angular/material/button';

@Component({
  selector: 'app-auth',
  templateUrl: './auth.component.html',
  styleUrls: ['./auth.component.scss'],
  standalone: true,
  imports: [
    CommonModule,
    MatCardModule,
    HttpClientModule,
    RouterModule,
    MatButtonModule
  ],
  providers: [ AuthGuard ]
})
export class AuthComponent {

  private auth: AuthService = inject(AuthService);
  private router: Router = inject(Router);

  cachedTeams: any[] = [];

  constructor() {
    // this.login();
    this.getCachedTeams();
  }

  login() {
    this.auth.loginFromLocalStorage().then(res => {
      if (res) {
        this.router.navigate(['/dashboard']);
      }
    })
  }


  getCachedTeams() {
    let t = localStorage.getItem('cached_teams');
    if (!t) { return; }

    let teams = JSON.parse(t);
    this.cachedTeams = Object.keys(teams).map((k: any) => {
      return { alias: k, name: teams[k] }
    });
  }

  openTeam(alias: string) {
    this.router.navigate([`teams/${alias}`])
  }

  clear() {
    localStorage.removeItem('cached_teams');
    this.cachedTeams = [];
  }
}
