import { Component, Input } from '@angular/core';
import { DataService } from 'src/services/data/data.service';
import { Observable } from 'rxjs';
import { Attribute } from 'src/interfaces/interfaces';
import { DetailsService } from 'src/services/details/details.service';
import { SaveThrowDetailsComponent } from '../save-throw-details/save-throw-details.component';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'save-throw-field',
  templateUrl: './save-throw-field.component.html',
  styleUrls: ['./save-throw-field.component.scss'],
})
export class SaveThrowFieldComponent {
  @Input() attributeName: string = '';
  public attribute: Attribute = {
    name: '',
    value: 0,
    proficiency: false,
    advantage: 'none',
  };

  private proficiencyBonus: number = 0;
  private attributeModifier: number = 0;
  public saveModifier: string = '0';

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

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

  private initAttributeSubscription(): void {
    const observable: Observable<Attribute> = eval(
      `this.dataAccessor.${this.attributeName}$`,
    );
    observable.subscribe((newValue: Attribute) => {
      this.attribute = newValue;
      // MIGRATION: Add default value for advantage
      if (this.attribute.advantage === undefined) {
        this.attribute.advantage = 'none';
      }
      this.attributeModifier = this.calculateAttributeModifier();
      this.saveModifier = this.calculateSaveModifier();
    });
  }

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

  private calculateAttributeModifier(): number {
    return Math.floor((this.attribute.value - 10) / 2);
  }

  public calculateSaveModifier(): string {
    let mod = this.attributeModifier;
    if (this.attribute.proficiency) {
      mod += this.proficiencyBonus;
    }
    if (mod > 0) {
      return '+' + mod;
    } else {
      return mod.toString();
    }
  }

  public openDetails(): void {
    this.detailsAccessor.openPanel(SaveThrowDetailsComponent, {
      attributeName: this.attributeName,
      saveModifier: this.saveModifier,
      advantage: this.attribute.advantage,
    });
    const resultSubscription = this.detailsAccessor.result$.subscribe(
      (result) => {
        if (result.state === 'update') {
          this.attribute.advantage = result.data.advantage;
          this.updateAttribute();
        }
        resultSubscription.unsubscribe();
      },
    );
  }

  public updateAttribute(): void {
    setTimeout(() => {
      this.dataAccessor.updateAttribute(this.attribute);
    });
  }
}
