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

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,
    public playerId?: string
  ) {
    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 {
      playerId: this.playerId,
      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 = ORIENTATION_ANGLES.north
        break
      case 'east':
        this.sprite.rotation = ORIENTATION_ANGLES.east
        break
      case 'south':
        this.sprite.rotation = ORIENTATION_ANGLES.south
        break
      case 'west':
        this.sprite.rotation = ORIENTATION_ANGLES.west
        break
    }
    this.orientation = value
  }

  clone(): Tile {
    const copy = new Tile(this.id, this.ticker, this.pips, this.scale, this.playerId)
    copy.selected = this.selected
    copy.orientation = this.orientation
    return copy
  }
}
