import { CommonModule } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { Component, EventEmitter, inject, Inject, Output } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatSnackBar } from '@angular/material/snack-bar';
import { Player } from '../../../../../../model';
import { AuthService } from 'src/app/modules/auth.service';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-player-details',
  templateUrl: './player-details.component.html',
  styleUrls: ['./player-details.component.scss'],
  standalone: true,
  imports: [CommonModule, MatSlideToggleModule]
})
export class PlayerDetailsComponent {

  player: Player;
  loading: boolean = false;
  private auth: AuthService = inject(AuthService);

  @Output('onReload') changed = new EventEmitter();

  constructor(@Inject(MAT_DIALOG_DATA) public data: DialogData, private http: HttpClient, private snackBar: MatSnackBar) {
    this.player = data.player;
  }


  get isAdmin() {
    return this.auth.isAdmin;
  }

  setPlayerActive(event: any) {
    this.loading = true;
    const copy = { ...this.player }
    this.player.active = event.checked;
    this.http.put<Player>(`${environment.apiUrl}teams/${this.player.team.id}/players`, this.player).subscribe({
      next: r => {
        this.changed.emit();
      },
      error: e => { 
        this.player.active = copy.active;

        this.snackBar.open('Spieler konnte nicht aktualisiert werden', undefined, {
          duration: 5000,
          panelClass: 'snackbar_error'
        })

       },
       complete: () => { this.loading = false; }
    })
  }
}

interface DialogData {
  player: Player;
}
