let preMarkerIndex = 0
const fs = wx.getFileSystemManager()

const downloadAndCache = (url, cacheKey) => {
  return new Promise((resolve, reject) => {
    wx.downloadFile({
      url,
      success(res) {
        if (res.statusCode === 200) {
          preMarkerIndex++
          const fileEnd = res.tempFilePath.split('.').slice(-1)[0]
          const filePath = `${wx.env.USER_DATA_PATH}/marker-ar-${preMarkerIndex}.${fileEnd}`
          fs.saveFile({
            filePath,
            tempFilePath: res.tempFilePath,
            success(res) {
              wx.setStorageSync(cacheKey, res.savedFilePath)
              resolve(res.savedFilePath)
            }
          })
        } else {
          reject(new Error('download failed:' + res.statusCode))
        }
      },
      fail: reject
    })
  })
}

export const clearImageCache = (cacheKey => {
  if (cacheKey) {
    const cachedPath = wx.getStorageSync(cacheKey)
    if (cachedPath) {
      try {
        wx.removeSavedFile({ filePath: cachedPath })
      } catch (e) {
        console.warn('删除文件失败', e)
      }
    }
    wx.removeStorageSync(cacheKey)
  } else {
    // 清空所有图片缓存
    const info = wx.getStorageInfoSync()
    info.keys.forEach(key => {
      if (key.startsWith('image_cache_')) {
        const cachedPath = wx.getStorageSync(key)
        try {
          wx.removeSavedFile({ filePath: cachedPath })
        } catch (e) {
          console.warn('删除文件失败', e)
        }
        wx.removeStorageSync(key)
      }
    })
  }
})

export const getCachedImage = (url, cacheKey) => {
  return new Promise((res, rej) => {
    const cachedPath = wx.getStorageSync(cacheKey)

    if (cachedPath) {
      wx.getFileInfo({
        filePath: cachedPath,
        success() {
          res(cachedPath)
        },
        fail() {
          downloadAndCache(url, cacheKey).then(res).catch(rej)
        }
      })
    } else {
      downloadAndCache(url, cacheKey).then(res).catch(rej)
    }
  })
}

export const hash = (str) => {
  let hash = 0
  for (let i = 0; i < str.length; i++) {
    hash = ((hash << 5) - hash) + str.charCodeAt(i)
    hash |= 0
  }
  return hash.toString()
}