import { LiveAnnouncer } from '@angular/cdk/a11y';
import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatSort, Sort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { Router } from '@angular/router';
import { AuthService } from '../../auth.service';
import { TeamsService } from '../teams.service';
import { DetailsComponent } from './details/details.component';
import { Player } from 'src/app/model';
import { PenaltiesComponent } from '../../../shared/penalties/penalties.component';

@Component({
  selector: 'app-overview',
  templateUrl: './overview.component.html',
  styleUrls: ['./overview.component.scss']
})
export class OverviewComponent implements OnInit, AfterViewInit {

  displayedColumns: string[] = ['firstName', 'lastName', 'balance'];
  dataSource: any;

  @ViewChild(MatSort) sort!: MatSort;

  constructor(public teamsService: TeamsService
    , private _liveAnnouncer: LiveAnnouncer
    , public dialog: MatDialog, private authService: AuthService
    , private router: Router) {}
  ngAfterViewInit(): void {
    this.dataSource.sort = this.sort;
  }


  ngOnInit(): void {
    if (this.teamsService.team && this.teamsService.team.players) {
      this.dataSource = new MatTableDataSource(this.teamsService.team.players.filter((p: Player) => p.active));
      this.addCachedTeam();
    }
  }

  addCachedTeam() {
    let t = localStorage.getItem('cached_teams');
    let teams: any = {};
    if (t) { 
      teams = JSON.parse(t);
      
     }
    const key = this.teamsService.team.alias as any;
    const name = this.teamsService.team.name as any;
    teams[key] = name;
    localStorage.setItem('cached_teams', JSON.stringify(teams));
  }


  getTotalBalance(): number {
    if (!this.teamsService || !this.teamsService.team || !this.teamsService.team.players) { return 0 }
    const sum = this.teamsService.team.players.filter((p: Player) => p.active).reduce((acc: any, succ: { balance: any; }) => acc + succ.balance, 0);
    return sum;
  }
  /** Announce the change in sort state for assistive technology. */
  announceSortChange(sortState: any) {
    // This example uses English messages. If your application supports
    // multiple language, you would internationalize these strings.
    // Furthermore, you can customize the message to add additional
    // details about the values being sorted.
    if (sortState.direction) {
      this._liveAnnouncer.announce(`Sorted ${sortState.direction}ending`);
    } else {
      this._liveAnnouncer.announce('Sorting cleared');
    }
  }
  
  openDetails(row: any) {
    this.dialog.open(DetailsComponent, {
      width: '500px',
      enterAnimationDuration: 500,
      data: { user: row }
    })
  }

  onLoginClick() {
    if (this.authService.isLoggedIn()) { return; }

    this.router.navigate(['auth'])
  }


  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }

  openPenalties() {
    this.dialog.open(PenaltiesComponent, {
      data: this.teamsService.team.id,
      height: '80vh'
    })
  }

}
