export interface GyroscopeControllerCallbacks {
  onSample: (x: number, y: number, z: number) => void
  onError: (message: string) => void
}

export class GyroscopeController {
  callbacks: GyroscopeControllerCallbacks
  listening: boolean
  starting: boolean
  gyroCallback: ((result: WechatMiniprogram.OnGyroscopeChangeCallbackResult) => void) | null

  constructor(callbacks: GyroscopeControllerCallbacks) {
    this.callbacks = callbacks
    this.listening = false
    this.starting = false
    this.gyroCallback = null
  }

  start(): void {
    if (this.listening || this.starting) {
      return
    }

    if (typeof wx.startGyroscope !== 'function' || typeof wx.onGyroscopeChange !== 'function') {
      this.callbacks.onError('当前环境不支持陀螺仪监听')
      return
    }

    const callback = (result: WechatMiniprogram.OnGyroscopeChangeCallbackResult) => {
      if (
        typeof result.x !== 'number'
        || typeof result.y !== 'number'
        || typeof result.z !== 'number'
        || Number.isNaN(result.x)
        || Number.isNaN(result.y)
        || Number.isNaN(result.z)
      ) {
        return
      }

      this.callbacks.onSample(result.x, result.y, result.z)
    }

    this.gyroCallback = callback
    wx.onGyroscopeChange(callback)
    this.starting = true
    wx.startGyroscope({
      interval: 'game',
      success: () => {
        this.starting = false
        this.listening = true
      },
      fail: (res) => {
        this.starting = false
        this.detachCallback()
        this.callbacks.onError(res && res.errMsg ? res.errMsg : 'startGyroscope failed')
      },
    })
  }

  stop(): void {
    this.detachCallback()
    wx.stopGyroscope({
      complete: () => {},
    })
    this.starting = false
    this.listening = false
  }

  destroy(): void {
    this.stop()
  }

  private detachCallback(): void {
    if (!this.gyroCallback) {
      return
    }

    if (typeof wx.offGyroscopeChange === 'function') {
      wx.offGyroscopeChange(this.gyroCallback)
    }

    this.gyroCallback = null
  }
}
