import { Component, Input, Output, EventEmitter } from '@angular/core';
import { NgbTypeaheadModule } from '@ng-bootstrap/ng-bootstrap';
import { Observable, OperatorFunction } from 'rxjs';
import { debounceTime, distinctUntilChanged, map } from 'rxjs/operators';
import { FormsModule } from '@angular/forms';
import { JsonPipe } from '@angular/common';
import { SpellsService } from 'src/services/spells/spells.service';
import { FormControl, ReactiveFormsModule } from '@angular/forms';

@Component({
  selector: 'add-card',
  templateUrl: './add-card.component.html',
  styleUrl: './add-card.component.scss',
})
export class AddCardComponent {
  @Input() level!: number;

  @Output() createNewSpell = new EventEmitter<any>();
  @Output() onSpellSelected = new EventEmitter<any>();

  public newSpellName: string = '';
  private availableSpells: string[] = [];
  public isModification: boolean | undefined;

  public constructor(private spellsAccessor: SpellsService) {}

  public ngOnInit(): void {
    this.availableSpells = this.spellsAccessor.getListOfSpells(this.level);
    this.spellsAccessor.closeSubject$.subscribe((level) => {
      if (level !== this.level) {
        this.resetThis();
      }
    });
  }

  // Enlarged view

  public emitNewSpell(): void {
    this.createNewSpell.emit(this.level);
    this.resetThis();
  }

  public continueToSpellSelection(modify: boolean): void {
    this.isModification = modify;
    this.spellsAccessor.closeAllOthers(this.level);
  }

  public spellSelected(spellname: any): void {
    const response = {
      spell: this.spellsAccessor.getSpell(spellname),
      isToModify: this.isModification,
    };
    this.onSpellSelected.emit(response);
    this.resetThis();
  }

  public resetThis(): void {
    this.newSpellName = '';
    this.isModification = undefined;
  }

  public search: OperatorFunction<string, readonly string[]> = (
    text$: Observable<string>
  ) =>
    text$.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      map((term) =>
        term.length < 2
          ? []
          : this.availableSpells
              .filter((v) => v.toLowerCase().indexOf(term.toLowerCase()) > -1)
              .slice(0, 5)
      )
    );
}
