import { Component, inject, TemplateRef } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { DataService } from 'src/services/data/data.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-character-picker',
  templateUrl: './character-picker.component.html',
  styleUrls: ['./character-picker.component.scss'],
})
export class CharacterPickerComponent {
  public characters: any[] = [];
  public currentCharacter: string = '';
  private modalService = inject(NgbModal);

  public constructor(public dataService: DataService, private Router: Router) {
    this.dataService.dataLoaded = false;
    this.dataService.getCollection('characters').then((characters: any) => {
      this.characters = characters;
    });
  }

  public addCharacter() {
    this.Router.navigate(['character/creator']);
  }

  open(content: TemplateRef<any>, index: number) {
    this.currentCharacter = this.characters[index].name;
    this.modalService
      .open(content, { ariaLabelledBy: 'modal-basic-title' })
      .result.then(
        (result) => {},
        (reason) => {
          if (reason == 'delete') {
            this.deleteCharacter(index);
          }
        }
      );
  }

  public deleteCharacter(index: number) {
    this.characters.splice(index, 1);
    this.dataService.deleteCollection(this.currentCharacter);
    this.dataService.deleteCollection('characters');
    setTimeout(() => {
      this.dataService.setCollection('characters', this.characters);
    }, 1000);
  }

  public selectCharacter(character: any) {
    console.log(character);
    sessionStorage.setItem('characterName', character.name);
    this.Router.navigate(['journal']);
  }
}
