import {
  Component,
  Input,
  Output,
  EventEmitter,
  Renderer2,
  ElementRef,
} from '@angular/core';
import { DataService } from 'src/services/data/data.service';
import { ListService } from 'src/services/list/list.service';

@Component({
  selector: 'character-card',
  templateUrl: './character-card.component.html',
  styleUrls: ['./character-card.component.scss'],
})
export class CharacterCardComponent {
  @Input() isTouchscreen: boolean = false;
  @Input() character: string = '';
  @Output() delete: EventEmitter<string> = new EventEmitter<string>();
  @Output() select: EventEmitter<string> = new EventEmitter<string>();
  public characterData: any = undefined;
  public image: any;
  public races: any;
  public classes: any;
  private touchStartX: number = 0;

  constructor(
    private dataAccessor: DataService,
    private list: ListService,
    private renderer: Renderer2,
    private el: ElementRef,
  ) {
    this.races = this.list.races;
    this.classes = this.list.classes;
  }

  ngOnInit() {
    this.loadCharacterData();
    this.renderer.listen(
      this.el.nativeElement,
      'touchstart',
      this.onTouchStart.bind(this),
    );
    this.renderer.listen(
      this.el.nativeElement,
      'touchend',
      this.onTouchEnd.bind(this),
    );
  }

  onTouchStart(event: any) {
    this.touchStartX = event.touches[0].clientX;
  }

  onTouchEnd(event: any) {
    const touchEndX = event.changedTouches[0].clientX;
    if (touchEndX > this.touchStartX + 50) {
      document.getElementById('delete-button')?.classList.add('show');
    } else if (touchEndX < this.touchStartX - 50) {
      document.getElementById('delete-button')?.classList.remove('show');
    }
  }

  public loadCharacterData(): void {
    this.dataAccessor
      .getData(this.character, 'characterData')
      .then((characterData: any) => {
        this.characterData = characterData;
      });
    this.dataAccessor.getData(this.character, 'image').then((image: any) => {
      this.image = image.value;
    });
  }

  public deleteCharacter(): void {
    this.delete.emit();
  }

  public selectCharacter(): void {
    this.select.emit();
  }
}
