var sprite = {}

var graphics = use('graphics')
var render   = use('render')
var draw2d   = use('draw2d')
var sprite = use('sprite')

var SPRITE  = Symbol()   /* raw C sprite                    */
var POS     = Symbol()   /* cached JS copies of simple data */
var ROT     = Symbol()
var SCALE   = Symbol()
var SKEW    = Symbol()
var CENTER  = Symbol()
var COLOR   = Symbol()
var IMAGE = Symbol()

var ursprite = {
  get pos()  { return this[POS] },
  set pos(v) {
    this[POS]      = v
    this[SPRITE].pos = v
  },

  get center() { return this[CENTER] },
  set center(v){
    this[CENTER]       = v
    this[SPRITE].center = v
  },

  get rotation() { return this[ROT] },
  set rotation(t){
    this[ROT]            = t
    this[SPRITE].rotation = t * 2*Math.PI  /* C expects radians */
    this[SPRITE].set_affine()
  },

  get scale() { return this[SCALE] },
  set scale(v){
    this[SCALE]       = v
    this[SPRITE].scale = v
    this[SPRITE].set_affine()
  },

  get skew() { return this[SKEW] },
  set skew(v){
    this[SKEW]       = v
    this[SPRITE].skew = v
    this[SPRITE].set_affine()
  },

  get layer() { return this[SPRITE].layer },
  set layer(n){ this[SPRITE].layer = n },

  get color() { return this[COLOR] },
  set color(v){
    this[COLOR]       = v
    this[SPRITE].color = v
  },

  move(mv) { this[SPRITE].move(mv) },
  moveto(p){
    this.pos = p
  },
  
  get image() { return this[IMAGE] },
  set image(img) {
    this[IMAGE] = img
    this[SPRITE].set_image(img)
  }
}

var _sprites = []

var def_sprite = Object.freeze({
  pos: [0,0],
  rotation: 0,
  scale: [1,1],
  center: [0,0],
  color: [1,1,1,1],
  skew: [0,0],
  layer: 0,
})

sprite.create = function(image, info) {
  info.__proto__ = def_sprite
  var sp = Object.create(ursprite)
  sp[SPRITE] = new sprite(info)
  sp.image = graphics.texture(image)

  _sprites.push(sp)
  return sp
}

sprite.forEach = fn => { for (let s of _sprites) fn(s) }
sprite.values  = ()  => _sprites.slice()
sprite.geometry= ()  => graphics.make_sprite_mesh(_sprites)

var raws = []
sprite.queue = function() {
  if (raws.length != _sprites.length)
    raws.length = _sprites.length
    
  for (var i = 0; i < _sprites.length; i++) raws[i] = _sprites[i]
  return graphics.make_sprite_queue(_sprites.map(x => x[SPRITE]))
} 

return sprite
