import { Component } from '@angular/core';
import { ClassService } from 'src/services/class/class.service';
import { DataService } from 'src/services/data/data.service';
import { ModalService } from 'src/services/modal/modal.service';
import { AbilityModalComponent } from '../../journal-stats/ability-panel/ability-table/ability-modal/ability-modal.component';
import { Ability, Trait } from 'src/interfaces/interfaces';
import { TraitModalComponent } from '../../journal-stats/ability-panel/trait-table/trait-modal/trait-modal.component';

@Component({
  selector: 'class',
  templateUrl: './class.component.html',
  styleUrl: './class.component.scss',
})
export class ClassComponent {
  public className: string = '';
  public class: any;
  public constructor(
    private classAccessor: ClassService,
    private dataAccessor: DataService,
    private modalAccessor: ModalService,
  ) {}

  public ngOnInit(): void {
    this.className = this.dataAccessor.characterData.class;
    this.class = this.classAccessor.getClassDetails(this.className);
  }

  public addFeature(feature: any) {
    if ('ability' in feature) {
      this.addAbility(feature);
    } else {
      this.addTrait(feature);
    }
  }

  private addAbility(feature: any) {
    let index = feature.name.indexOf('Optional');
    if (index > -1) {
      feature.name = feature.name.slice(index, 8);
    }
    let ability: Ability = {
      name: feature.name,
      shortDescription: '',
      longDescription: feature.description,
      cost: '',
      charges: 0,
      currentlyUsedCharges: 0,
    };
    this.modalAccessor.openModal(AbilityModalComponent, {
      ability: ability,
      isUpdate: true,
      isAddedFromCharacter: true,
    });
    const resultSubscription = this.modalAccessor.result$.subscribe(
      (result) => {
        if (result.state === 'update' || result.state === 'add') {
          let ability = this.dataAccessor.abilities;
          ability.push(result.data);
          this.dataAccessor.abilities = ability;
        }
        resultSubscription.unsubscribe();
      },
    );
  }

  private addTrait(feature: any) {
    let index = feature.name.indexOf('Optional');
    if (index > -1) {
      feature.name = feature.name.slice(index, 8);
    }
    let trait: Trait = {
      name: feature.name,
      shortDescription: '',
      longDescription: feature.description,
      origin: 'Class',
    };
    this.modalAccessor.openModal(TraitModalComponent, {
      trait: trait,
      isUpdate: true,
      isAddedFromCharacter: true,
    });
    const resultSubscription = this.modalAccessor.result$.subscribe(
      (result) => {
        if (result.state === 'update' || result.state === 'add') {
          let traits = this.dataAccessor.traits;
          traits.push(result.data);
          this.dataAccessor.traits = traits;
        }
        resultSubscription.unsubscribe();
      },
    );
  }
}
