import { Injectable } from '@angular/core';
import { DataService } from 'src/services/data/data.service';

@Injectable({
  providedIn: 'root',
})
export class UtilsService {
  private spellcastingAttribute: string = 'wisdom'; // backup
  private proficiencyBonus: number = 2;
  private attributeValue: number = 0;
  public spellAttackModifier: string = '';
  public spellSaveDC: number = 0;

  public constructor(private dataAccessor: DataService) {
    this.spellcastingAttribute =
      this.dataAccessor.spellslots.spellcastingAttribute;

    this.subscribeToProficiency();
    this.subscribeToAttribute();
  }

  /////////////////////////////////////////////
  //        SPELLCASTING MODIFIERS           //
  /////////////////////////////////////////////

  private calculateModifiers(): void {
    const spellcastingAttribute = this.spellcastingAttribute;
    if (spellcastingAttribute !== undefined) {
      const modifier = Math.floor((this.attributeValue - 10) / 2);
      let attackBonus = modifier + this.proficiencyBonus;
      if (attackBonus >= 0) {
        this.spellAttackModifier = '+' + attackBonus;
      } else {
        this.spellAttackModifier = attackBonus.toString();
      }
      this.spellSaveDC = 8 + modifier + this.proficiencyBonus;
    }
  }

  private subscribeToAttribute(): void {
    if (
      this.spellcastingAttribute !== undefined &&
      this.spellcastingAttribute !== null
    ) {
      const command =
        'this.dataAccessor.' +
        this.spellcastingAttribute.toLowerCase() +
        '$.subscribe((attribute) => {this.attributeValue = attribute.value; this.calculateModifiers();});';
      eval(command);
    }
  }

  private subscribeToProficiency(): void {
    this.dataAccessor.proficiency$.subscribe((value: number) => {
      this.proficiencyBonus = value;
      this.calculateModifiers();
    });
  }

  /////////////////////////////////////////////
  //             PLACEHOLDER                 //
  /////////////////////////////////////////////
}
