import { Component } from '@angular/core';
import { DataService } from 'src/services/data/data.service';
import { DetailsService } from 'src/services/details/details.service';
import { LifeDetailsComponent } from './life-details/life-details.component';

@Component({
  selector: 'life',
  templateUrl: './life.component.html',
  styleUrls: ['./life.component.scss'],
})
export class LifeComponent {
  public maxHitPoints: number = 0;
  public currentHitPoints: number = 0;
  public temporaryHitPoints: number = 0;

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

  public constructor(
    public dataAccessor: DataService,
    public detailsAccessor: DetailsService,
  ) {}

  ngOnInit(): void {
    this.dataAccessor.hitPoints$.subscribe((hitPoints: any) => {
      this.maxHitPoints = hitPoints.maxHitPoints;
      this.currentHitPoints = hitPoints.currentHitPoints;
      this.temporaryHitPoints = hitPoints.temporaryHitPoints;
      this.calculatePercentages();
    });
  }

  //   const hitPointsData = this.dataAccessor.hitPoints;
  //   this.maxHitPoints = hitPointsData.maxHitPoints;
  //   this.currentHitPoints = hitPointsData.currentHitPoints;
  //   this.temporaryHitPoints = hitPointsData.temporaryHitPoints;
  //   this.hitDice = this.dataAccessor.hitDice;
  //   this.calculatePercentages();
  // }

  public addHitPoints(): void {
    if (this.currentHitPoints < this.maxHitPoints) {
      this.currentHitPoints = this.currentHitPoints + 1;
      this.updateDatabase();
      this.calculatePercentages();
    }
  }

  public removeHitPoints(): void {
    if (this.temporaryHitPoints > 0) {
      this.temporaryHitPoints = this.temporaryHitPoints - 1;
      this.updateDatabase();
      this.calculatePercentages();
    } else if (this.currentHitPoints > 0) {
      this.currentHitPoints = this.currentHitPoints - 1;
      this.updateDatabase();
      this.calculatePercentages();
    }
  }

  public addTemporaryHitPoints(): void {
    if (this.currentHitPoints > 0) {
      this.temporaryHitPoints = this.temporaryHitPoints + 1;
      this.updateDatabase();
      this.calculatePercentages();
    }
  }

  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;
  }

  public openDetailsPanel(): void {
    this.detailsAccessor.openPanel(LifeDetailsComponent, {});
  }

  public updateDatabase() {
    this.dataAccessor.updateHitPoints({
      maxHitPoints: this.maxHitPoints,
      currentHitPoints: this.currentHitPoints,
      temporaryHitPoints: this.temporaryHitPoints,
    });
  }
}
