import * as Phaser from "phaser";

class Card {
  scene: Phaser.Scene | null = null;
  group: Phaser.GameObjects.Group | null = null;
  sprites = [];
  isFaceUp: boolean = true;
  characterName: string | null = null;
  isFlipping: boolean = false;

  constructor(scene: Phaser.Scene, x: number, y: number, characterName: string) {
    this.scene = scene;
    this.characterName = characterName;

    const cardBackground: Phaser.GameObjects.Image = new Phaser.GameObjects.Image(scene, x, y, 'card-bg', 0)
    const cardShadow: Phaser.GameObjects.Image = new Phaser.GameObjects.Image(scene, x, y, 'card-shadow', 0)
    const character: Phaser.GameObjects.Image = new Phaser.GameObjects.Image(scene, x, y, 'character-' + characterName + '-card', 0)

    const cardGroup: Phaser.GameObjects.Group = new Phaser.GameObjects.Group(scene)

    cardGroup.add(cardShadow)
    cardGroup.add(cardBackground)
    cardGroup.add(character)

    this.group = cardGroup

    character.setInteractive();
    scene.add.existing(cardShadow)
    scene.add.existing(cardBackground)
    scene.add.existing(character)

    scene.add.existing(cardGroup)

    this.sprites.push({ sprite: cardShadow, offsetX: -5, offsetY: -5 })
    this.sprites.push({ sprite: cardBackground, offsetX: 0, offsetY: 0 })
    this.sprites.push({ sprite: character, offsetX: 0, offsetY: 0 })
  }
  onEvent(eventName: any, fn: any) {
    const sprite = this.sprites[this.sprites.length - 1].sprite
    console.log(sprite, eventName, fn)
    sprite.on(eventName, fn, this.scene)
  }
  flip() {
    if (this.isFlipping) {
      return;
    }
    this.isFlipping = true;

    const ease = 'Sine.easeIn'
    const duration = 100
    const tween = this.scene?.tweens.add({
      targets: this.sprites.map(s => s.sprite),
      props: {
        scaleX: { value: 0, duration, yoyo: true },
      },
      ease,
      onComplete: () => {
        this.isFaceUp = !this.isFaceUp;
        this.isFlipping = false;
      }
    })
    this.scene?.tweens.add({
      targets: this.sprites[2].sprite,
      props: {
        texture: { value: this.isFaceUp ? 'card-bg' : 'character-' + this.characterName + '-card', duration: 0, delay: duration },
      },
      ease,
    })
  }
  moveTo(x: number, y: number) {
    this.scene?.tweens.add({
      targets: this.sprites.filter(s => s.offsetX === 0).map(s => s.sprite),
      props: {
        x: { value: x, duration: 1000 },
        y: { value: y, duration: 1000 }
      },
      ease: 'Expo.out'
    })
    this.scene?.tweens.add({
      targets: this.sprites.filter(s => s.offsetX != 0).map(s => s.sprite),
      props: {
        x: { value: x - 5, duration: 1000 },
        y: { value: y + 5, duration: 1000 }
      },
      ease: 'Expo.out'
    })
    //this.group?.setXY(x, y)
  }
  scaleTo(x: number, y: number) {
    this.group?.children.iterate((child) => child.setScale(x, y))
  }
}

export default Card;