var film2d = use('film2d')

var shape_proto = {
  type: 'shape',
  
  set_pos: function(x, y) {
    this.pos.x = x
    this.pos.y = y
    return this
  },

  destroy: function() {
    film2d.unregister(this._id)
  }
}

var defaults = {
  type: 'shape',
  shape_type: 'rect',  // 'rect', 'circle', 'ellipse', 'pill'
  
  // routing
  plane: 'default',
  layer: 0,
  groups: [],
  visible: true,
  
  // transform
  pos: {x: 0, y: 0},
  anchor_x: 0.5,
  anchor_y: 0.5,
  rotation: 0,
  
  // geometry
  width: 100,
  height: 100,
  
  // corner / radius controls (rect/pill)
  radius: 0,
  corner_style: 'round',  // 'round', 'bevel', 'scoop', 'notch', 'square'
  
  // edge / coverage
  feather: 0,
  stroke_thickness: 0,
  stroke_align: 'center',  // 'inside', 'center', 'outside'
  
  // dashed stroke
  dash_len: 0,
  gap_len: 0,
  dash_offset: 0,
  cap: 'butt',    // 'butt', 'square', 'round'
  join: 'miter',  // 'miter', 'bevel', 'round'
  miter_limit: 4,
  
  // fill/stroke colors
  fill: {r: 1, g: 1, b: 1, a: 1},
  stroke: {r: 0, g: 0, b: 0, a: 0},
  
  // blending
  blend: 'alpha',  // 'alpha', 'add', 'mul', 'screen'
  opacity: 1,
  
  // texture fill
  fill_tex: null,
  uv: {
    space: 'local',  // 'local', 'screen'
    scale: {x: 1, y: 1},
    offset: {x: 0, y: 0},
    rotate: 0
  },
  sampler: null
}

function make_shape(shape_type, props) {
  var data = object(defaults, props)
  
  // Ensure groups is array
  if (!data.groups) data.groups = []
  if (is_text(data.groups)) data.groups = [data.groups]
  
  var s = meme(shape_proto, data)
  film2d.register(s)
  return s
}

var shape2d = {
  rect: function(props) {
    return make_shape('rect', props)
  },
  
  circle: function(props) {
    // For circle, width == height == diameter
    var p = props || {}
    if (p.radius != null && p.width == null) {
      p.width = p.radius * 2
      p.height = p.radius * 2
    }
    return make_shape('circle', p)
  },
  
  ellipse: function(props) {
    return make_shape('ellipse', props)
  },
  
  pill: function(props) {
    return make_shape('pill', props)
  }
}

return shape2d
