var ble = require('../../services/ble')
var config = require('../../config/env')

Page({
  data: {
    statusBarHeight: 44,
    scanning: true,
    scanProgress: 0,
    regions: 0x7F,
    regionData: [],
    timeout: false,
    error: '',
    devMode: false
  },

  onBack: function () {
    wx.navigateBack({
      fail: function () {
        wx.reLaunch({ url: '/pages/index/index' })
      }
    })
  },

  onLoad: function (options) {
    var app = getApp()
    this.setData({
      statusBarHeight: app.globalData.statusBarHeight,
      regions: parseInt(options.regions) || 0x7F,
      devMode: config.__DEV__ || false
    })
    this.startScan()
  },

  startScan: function () {
    var self = this
    self.setData({ scanning: true, scanProgress: 0, timeout: false })

    this._progressTimer = setInterval(function () {
      var p = self.data.scanProgress + 2
      if (p > 98) p = 98
      self.setData({ scanProgress: p })
    }, 100)

    this._onStatus = function (status) {
      if (status.mode_state === 0x01) {
        self.setData({ scanProgress: 50 })
      } else if (status.mode_state === 0x04 || status.mode_state === 0x00) {
        clearInterval(self._progressTimer)
        self.setData({ scanning: false, scanProgress: 100 })
        var names = ble.getRegionName(status.region_mask || 0x7F)
        self.setData({ regionData: self.parseScanResults(names) })
      }
    }
    ble.on('status', this._onStatus)

    ble.queryStatus().catch(function () {})

    setTimeout(function () {
      clearInterval(self._progressTimer)
      if (!self.data.scanning) return
      self.setData({ scanning: false, timeout: true })
      wx.showToast({ title: '扫描超时，请重试', icon: 'none' })
    }, 5000)
  },

  parseScanResults: function (regions) {
    return regions.map(function (name) {
      return { region: name, pd: '待检测' }
    })
  },

  onUnload: function () {
    if (this._progressTimer) clearInterval(this._progressTimer)
    if (this._onStatus) ble.off('status', this._onStatus)
  },

  onNext: function () {
    var mask = this.data.regions || 0x7F
    ble.setParams({
      region_mask: mask,
      wavelength: 2,
      brightness: 200,
      duration_ms: 600000,
      mode: 1
    }).then(function () {
      return ble.startTreatment(mask)
    }).then(function () {
      wx.redirectTo({
        url: '/pages/treating/treating?regions=' + mask + '&wavelength=2&duration=600000&mode=1'
      })
    }).catch(function (err) {
      wx.showToast({ title: err.error_msg || '启动失败', icon: 'none' })
    })
  },

  onMockScanDone: function () {
    var self = this
    if (self._progressTimer) clearInterval(self._progressTimer)
    var mask = parseInt(self.data.regions) || 0x7F
    wx.redirectTo({
      url: '/pages/treating/treating?regions=' + mask +
        '&wavelength=2' +
        '&duration=600000' +
        '&mode=1'
    })
  }
})
