import { Component, Input, Output, EventEmitter, inject } from '@angular/core';
import { DataService } from 'src/services/data/data.service';
import { Spell } from 'src/interfaces/interfaces';
import { SpellsService } from 'src/services/spells/spells.service';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'add-card',
  templateUrl: './add-card.component.html',
  styleUrl: './add-card.component.scss',
})
export class AddCardComponent {
  @Input() level!: number;
  @Input() alreadyUsedSpells!: any[];
  @Output() onSpellSelected = new EventEmitter<any>();

  public newSpellName: string = '';
  private classAvailableSpells: any[] = [];
  private allAvailableSpells: any[] = [];
  public availableSpells: any[] = [];
  public isIdle: boolean = true;
  public showAll: boolean = false;

  private spellsAccessor = inject(SpellsService);
  private dataAccessor = inject(DataService);
  public translate: any = inject(TranslateService);

  public ngOnInit(): void {
    this.classAvailableSpells = this.spellsAccessor.getAvailableSpells(
      this.level,
      this.dataAccessor.characterData.class,
    );
    this.allAvailableSpells = this.spellsAccessor.getAvailableSpells(
      this.level,
    );
    this.filterSpellArray();
    this.spellsAccessor.closeSubject$.subscribe((level) => {
      if (level !== this.level) {
        this.resetThis();
      }
    });
  }

  public toggleShowAll(): void {
    this.showAll = !this.showAll;
    this.filterSpellArray();
  }

  public spellSelected(spell: any): void {
    this.onSpellSelected.emit(spell);
    this.resetThis();
  }

  public closeOthers(): void {
    this.spellsAccessor.closeAllOthers(this.level);
  }

  public resetThis(): void {
    this.newSpellName = '';
    this.isIdle = true;
    this.showAll = false;
  }

  public filterSpellArray(): void {
    let array = this.showAll
      ? this.allAvailableSpells
      : this.classAvailableSpells;
    if (this.newSpellName.length > 0) {
      this.availableSpells = array.filter(
        (spell) =>
          (spell.german
            .toLowerCase()
            .includes(this.newSpellName.toLowerCase()) ||
            spell.english
              .toLowerCase()
              .includes(this.newSpellName.toLowerCase())) &&
          !this.alreadyUsedSpells.includes(spell.id),
      );
    } else {
      this.availableSpells = array.filter(
        (spell) => !this.alreadyUsedSpells.includes(spell.id),
      );
    }
  }
}
