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

@Component({
  selector: 'app-life',
  templateUrl: './life.component.html',
  styleUrls: ['./life.component.scss'],
})
export class LifeComponent {
  public constructor(public dataAccessor: DataService) {}

  public maxHitPoints: number = 0;
  public currentHitPoints: number = 0;
  public temporaryHitPoints: number = 0;

  public currentHitPointsPercentage: number = 0;
  public temporaryHitPointsPercentage: number = 0;
  public missingHitPointsPercentage: number = 0;

  ngOnInit(): void {
    this.initMaxSubscription();
    this.initCurrentSubscription();
    this.initTemporarySubscription();
  }

  private initMaxSubscription(): void {
    this.dataAccessor.hitPointMaximum$.subscribe((newValue: any) => {
      this.maxHitPoints = newValue.value;
      this.calculatePercentages();
    });
  }

  private initCurrentSubscription(): void {
    this.dataAccessor.currentHitPoints$.subscribe((newValue: any) => {
      this.currentHitPoints = newValue.value;
      this.calculatePercentages();
    });
  }

  private initTemporarySubscription(): void {
    this.dataAccessor.temporaryHitPoints$.subscribe((newValue: any) => {
      this.temporaryHitPoints = newValue.value;
      this.calculatePercentages();
    });
  }

  public addHitPoints(): void {
    console.log('addCurrentHitPoints');
    if (this.currentHitPoints < this.maxHitPoints) {
      this.dataAccessor.updateCharacterData({
        name: 'currentHitPoints',
        value: this.currentHitPoints + 1,
      });
    }
  }

  public removeHitPoints(): void {
    if (this.temporaryHitPoints > 0) {
      this.dataAccessor.updateCharacterData({
        name: 'temporaryHitPoints',
        value: this.temporaryHitPoints - 1,
      });
    } else if (this.currentHitPoints > 0) {
      console.log('removeCurrentHitPoints');
      this.dataAccessor.updateCharacterData({
        name: 'currentHitPoints',
        value: this.currentHitPoints - 1,
      });
    }
  }

  public addTemporaryHitPoints(): void {
    if (this.currentHitPoints > 0) {
      this.dataAccessor.updateCharacterData({
        name: 'temporaryHitPoints',
        value: this.temporaryHitPoints + 1,
      });
    }
  }

  private calculatePercentages() {
    this.currentHitPointsPercentage =
      (this.currentHitPoints / this.maxHitPoints) * 100;
    this.temporaryHitPointsPercentage =
      (this.temporaryHitPoints / this.maxHitPoints) * 100;
    this.missingHitPointsPercentage =
      ((this.maxHitPoints - (this.currentHitPoints + this.temporaryHitPoints)) *
        100) /
      this.maxHitPoints;
  }

  // TODO: Set life: Modalmit dem man die Were genau einstellen kann
}
