import { ChangeDetectorRef, Component, NgZone, OnInit } from '@angular/core';
import { Player, AvalonStage } from '../../../entity/Avalon';
import { AvalonService } from '../../../services/avalon.service';
import { MsgBoxService } from '../../../services/msg-box.service';
import { ADIcon } from '../../../ui/alert-dlg/alert-dlg.model';
import { AvalonBase } from '../avalonBase';

@Component({
  selector: 'avalon-pick-teammate',
  templateUrl: './pick-teammate.component.html',
  styleUrls: ['./pick-teammate.component.scss']
})
export class PickTeammateComponent extends AvalonBase implements OnInit {

  constructor(
    protected cdRef: ChangeDetectorRef,
    protected avalonService: AvalonService,
    private ngZone: NgZone,
    private msgBoxService: MsgBoxService
  ) {
    super(cdRef, avalonService);
  }

  ngOnInit(): void {
  }

  toggleTeamMate(player: Player, value: boolean) {
    player.goingToQuest = value;
    this.cdRef.detectChanges();
  }

  public pickTeamMate() {
    let teamSize = this.players.filter(p => p.goingToQuest).length;
    if (teamSize == this.currentQuest.teamSize) {
      this.avalonService.data.stage = AvalonStage.TeamVote;
      this.clearVoteStatus();
      this.broadcastAll();
      this.avalonService.applyCdChange$.next();
    } else {
      this.ngZone.run(_ => {
        this.msgBoxService.show('任務編組錯誤!', { text: `本次任務出場人數為 ${this.currentQuest.teamSize} 人!`, icon: ADIcon.WARNING });
      });
    }
  }

  public changeLeader(newLeader: Player) {
    let oldLeader = this.players.find(p => p.isLeader);
    if (oldLeader) oldLeader.isLeader = false;
    newLeader.isLeader = true;

    for (let i = 0; i < this.players.length; i++) {
      const player = this.players[i];
      player.goingToQuest = false;
    }
    this.refreshAllInfo();
    this.cdRef.detectChanges();
  }

}
