import { Component, Input } from '@angular/core';
import { ModalService } from 'src/services/modal/modal.service';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';

@Component({
  selector: 'spellslots-modal',
  templateUrl: './spellslots-modal.component.html',
  styleUrls: ['./spellslots-modal.component.scss'],
})
export class SpellslotsModalComponent {
  @Input() public spellslots: any[] = [];
  @Input() public kiPoints: any;
  @Input() public showSpellslots: boolean = true;
  @Input() public isMonk: boolean = false;

  public kiNumbersArray: number[] = Array.from({ length: 20 }, (_, i) => i + 1);

  public constructor(public modalAccessor: ModalService) {}

  // Shows the spellslot container
  public onSpellslotsSwitchChanged(event: any): void {
    this.showSpellslots = event.checked;
  }

  // Shows the ki points container
  public onKiPointsSwitchChanged(event: any): void {
    this.kiPoints.showKiPoints = event.checked;
  }

  // Removes the specified spellslot level
  public removeSpellLevel(levelIndex: number): void {
    this.spellslots.splice(levelIndex, 1);
  }

  // adds a new spellslot level
  public addSpellLevel(): void {
    this.spellslots.push({
      totalSlots: 1,
      usedSlots: 0,
    });
  }

  public updateSlotsandPoints(): any {
    this.spellslots.forEach((level) => {
      level.usedSlots = Math.min(level.usedSlots, level.totalSlots);
    });
    this.kiPoints.usedPoints = Math.min(
      this.kiPoints.usedPoints,
      this.kiPoints.totalPoints,
    );
    const updatedSlotsAndPoints: any = {
      spellslots: {
        spellslots: this.spellslots,
        showSpellslots: this.showSpellslots,
      },
      kiPoints: this.kiPoints,
    };
    return updatedSlotsAndPoints;
  }

  private resultData(): any {
    return {
      spellslots: this.spellslots,
      kiPoints: this.kiPoints,
      showSpellslots: this.showSpellslots,
    };
  }

  // RESPONSES

  public cancel(): void {
    this.modalAccessor.handleModalClosing('cancel', undefined);
  }

  public update(): void {
    this.modalAccessor.handleModalClosing(
      'update',
      this.updateSlotsandPoints(),
    );
  }
}
