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

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

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

  ngOnInit(): void {
    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();
    });
  }

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

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

  public openDetails(): void {
    this.detailsAccessor.openPanel(AttributeDetailsComponent, {
      attribute: this.attribute,
      modifier: this.attributeModifier,
    });
    const resultSubscription = this.detailsAccessor.result$.subscribe(
      (result) => {
        if (result.state === 'update') {
          this.resistances = result.data.resistances;
          this.updateValue();
        }
        resultSubscription.unsubscribe();
      },
    );
  }
}
