export default class Drawer {
  constructor(options) {
    this.ctx = options.ctx
    this.canvas = options.canvas
    this.beforeDraw = []
    this.finishDraw = []
    this.tempList = []
    this.drawList = []
  }
  before (cb) {
    this.beforeDraw.push(cb)
    return this
  }
  draw (cb) {
    if (cb && typeof cb === 'function') {
      this.tempList.push((data) => {
        return new Promise((resolve) => {
          cb(resolve, data)
        })
      })
      this.drawList.push((data) => {
        return new Promise((resolve) => {
          cb(resolve, data)
        })
      })
    }
    return this
  }
  finished (cb) {
    this.finishDraw.push(cb)
    return this
  }

  async exec () {
    const draw = async (drawList) => {
      let tempResult = {}
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
      while (drawList.length) {
        const curCb = drawList.shift()
        tempResult = await curCb(tempResult)
      }
    }
    await draw(this.tempList)
    
    this.beforeDraw.forEach(item => {
      item()
    })
    await draw(this.drawList)
    setTimeout(() => {
      this.finishDraw.forEach(item => {
        item()
      })
    }, 0)
  }
}