import { Component, EventEmitter, Output } from '@angular/core';
import { DataService } from 'src/services/data/data.service';

@Component({
  selector: 'hit-dice',
  templateUrl: './hit-dice.component.html',
  styleUrls: ['./hit-dice.component.scss'],
})
export class HitDiceComponent {
  public hitDice: any;

  @Output() public setHitDice: EventEmitter<any> = new EventEmitter();

  constructor(private dataAccessor: DataService) {
    this.hitDice = this.dataAccessor.hitDice;
  }

  public ngOnInit(): void {
    this.correctHitDiceView();
  }

  public handleUsedHitDice(index: number, element: any): void {
    if (element.checked) {
      this.hitDice.diceUsed++;
      if (index + 1 !== this.hitDice.diceUsed) {
        this.correctHitDiceView();
      }
    } else {
      this.hitDice.diceUsed--;
      if (index !== this.hitDice.diceUsed) {
        this.correctHitDiceView();
      }
    }
    this.updateDatabase();
  }

  private correctHitDiceView(): void {
    const totalHitDice = this.hitDice.diceNumber;
    const usedHitDice = this.hitDice.diceUsed;

    for (let index = 0; index < usedHitDice; index++) {
      setTimeout(() => {
        (
          document.getElementById('checkbox' + index) as HTMLInputElement
        ).checked = true;
      });
    }
    for (let index = usedHitDice; index < totalHitDice; index++) {
      setTimeout(() => {
        (
          document.getElementById('checkbox' + index) as HTMLInputElement
        ).checked = false;
      });
    }
  }

  public getArray(length: number): any[] {
    return Array.from({ length: length });
  }

  public addDice(): void {
    this.hitDice.diceNumber++;
    this.updateDatabase();
  }

  public removeDice(): void {
    if (this.hitDice.diceNumber > 1) {
      this.hitDice.diceNumber--;
    }
    if (this.hitDice.diceUsed > this.hitDice.diceNumber) {
      this.hitDice.diceUsed = this.hitDice.diceNumber;
    }
    this.updateDatabase();
  }

  public updateDatabase(): void {
    this.dataAccessor.hitDice = this.hitDice;
  }
}
