import { Texture, Ticker } from 'pixi.js'
import { SpriteBase } from '@/game/SpriteBase'

export class Tile extends SpriteBase {
  selected: boolean = false
  orientation: string
  // sprite: Sprite = new Sprite()
  // private _interactive: boolean = false

  constructor(
    public id: string,
    ticker?: Ticker,
    public pips?: [number, number],
    scale: number = 1
  ) {
    super(ticker, scale)
    this.id = id
    // this.ticker = ticker
    this.sprite.texture = this.createTexture()
    this.sprite.anchor.set(0.5)
    this.sprite.height = 100 * this.scale
    this.sprite.width = 50 * this.scale
    this.pips = pips
    this.orientation = 'north'
  }

  toPlain() {
    return {
      id: this.id,
      pips: this.pips,
      orientation: this.orientation,
      x: this.sprite.x,
      y: this.sprite.y,
      width: this.sprite.width,
      height: this.sprite.height
    }
  }

  equals(tile: Tile | undefined): boolean {
    if (this.pips === undefined || tile === undefined || tile.pips === undefined) return false
    return (
      (this.pips[0] === tile.pips[0] && this.pips[1] === tile.pips[1]) ||
      (this.pips[0] === tile.pips[1] && this.pips[1] === tile.pips[0])
    )
  }

  createTexture(): Texture {
    if (this.pips !== undefined) {
      const sortedInversrPips = this.pips.slice().sort((a, b) => b - a)
      return Texture.from(`tile-${sortedInversrPips[0]}_${sortedInversrPips[1]}`)
    } else {
      return Texture.from('tile-back')
    }
  }

  reScale(scale: number) {
    this.scale = scale
    this.sprite.height = 100 * this.scale
    this.sprite.width = 50 * this.scale
  }

  isPair(): boolean {
    return this.pips !== undefined && this.pips[0] === this.pips[1]
  }
  isVertical(): boolean {
    return this.orientation === 'north' || this.orientation === 'south'
  }

  setOrientation(value: string) {
    switch (value) {
      case 'north':
        this.sprite.rotation = 0
        break
      case 'east':
        this.sprite.rotation = Math.PI / 2
        break
      case 'south':
        this.sprite.rotation = Math.PI
        break
      case 'west':
        this.sprite.rotation = (3 * Math.PI) / 2
        break
    }
    this.orientation = value
  }
}
