import { Component, Input } from '@angular/core';
import { Attribute } from 'src/interfaces/attribute';
import { DataService } from 'src/services/data/data.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-attribute-field',
  templateUrl: './attribute-field.component.html',
  styleUrls: ['./attribute-field.component.scss'],
})
export class AttributeFieldComponent {
  @Input() attributeName: string = '';
  public attribute: Attribute = { name: '', value: 0 };
  public attributeModifier: string = '0';
  public saveModifier: string = '0';
  public proficiencyBonus: number = 0;

  public attributeNames: any = {
    strength: 'Stärke',
    dexterity: 'Geschicklichkeit',
    constitution: 'Konstitution',
    intelligence: 'Intelligenz',
    wisdom: 'Weisheit',
    charisma: 'Charisma',
  };

  public constructor(public dataAccessor: DataService) {}

  ngOnInit(): void {
    this.initProficiencySubscription();
    this.initAttributeSubscription();
  }

  private initAttributeSubscription(): void {
    const observable: Observable<Attribute> = eval(
      `this.dataAccessor.${this.attributeName}$`
    );
    observable.subscribe((newValue: Attribute) => {
      this.attribute = newValue;
      this.attributeModifier = this.calculateModifier();
      this.saveModifier = this.calculateSaveModifier();
    });
  }

  private initProficiencySubscription(): void {
    this.dataAccessor.proficiency$.subscribe((newValue: any) => {
      this.proficiencyBonus = newValue.value;
      this.saveModifier = this.calculateSaveModifier();
    });
  }

  public updateValue(): void {
    this.dataAccessor.updateAttribute({
      name: this.attribute.name,
      value: this.attribute.value,
      proficiency: this.attribute.proficiency,
    });
  }

  public calculateModifier(): string {
    const mod: number = Math.floor((this.attribute.value - 10) / 2);
    if (mod > 0) {
      return '+' + mod;
    } else {
      return mod.toString();
    }
  }

  public calculateSaveModifier(): string {
    let mod: number = Math.floor((this.attribute.value - 10) / 2);
    if (this.attribute.proficiency) {
      mod += this.proficiencyBonus;
    }
    if (mod > 0) {
      return '+' + mod;
    } else {
      return mod.toString();
    }
  }
}
