/**
 * 游戏基础的精灵类
 */
function Sprite(imgSrc = '', x = 0, y = 0, width = 0, height = 0,iscircle=false) {

  this._width = width
  this._height = height

  this.x = x
  this.y = y
  this._name = ""
  this._fillStyle = "#ffffff"
  this._globalAlpha = 1;
  this.visible = true
  this.iscircle=iscircle
  this.src = imgSrc

}

Sprite.prototype = {
  set name(tex) {
    this._name = tex;
  },

  get name() {
    return this._name;
  },

  set width(tex) {
    this._width = tex;
  },

  get width() {
    return this._width;
  },

  set height(tex) {
    this._height = tex;
  },

  get height() {
    return this._height;
  },

  set fillStyle(tex) {
    this._fillStyle = tex;
  },

  set iscircle(iscircle) {
    this._iscircle = iscircle;
  },
  get globalAlpha() {
    return this._globalAlpha;
  },

  set globalAlpha(tex) {
    this._globalAlpha = tex;
  },

  get fillStyle() {
    return this._fillStyle;
  },

  set src(tex) {
    this._src = tex;
    if (tex != '' && tex != null) {
      this.img = wx.createImage();
      this.img.src = tex;
      this.img.onload = () => {
        if (this.ctx != null)
          if (this.parent) {
            this.parent.drawToCanvas(this.ctx);

          } else {
            this.drawToCanvas(this.ctx);
          }
      };
    }
  },

  get src() {
    return this._src;
  }

}

Sprite.prototype.position = function(x, y) {

  this.x = x;
  this.y = y;

}

/**
 * 将精灵图绘制在canvas上
 */
Sprite.prototype.drawToCanvas = function(ctx) {

  if (!this.visible)
    return
  this.ctx = ctx;
  ctx.globalAlpha = this.globalAlpha;
  if (this.src != '' && this.src != null) {
    if (this._iscircle) {
      ctx.save();
      let r = Math.ceil(this.width * 0.5) ;
      ctx.arc(this.x + r, this.y + r, r, 0, Math.PI * 2);
      ctx.clip();
      ctx.drawImage(this.img, this.x, this.y, 2 * r, 2 * r);
      ctx.restore();
    } else {
      ctx.drawImage(this.img, this.x, this.y, this.width, this.height)
    }
  } else {
    ctx.fillStyle = this.fillStyle;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
}

module.exports.Sprite = Sprite;