import TableHelper from './lib/TableHelper'
import User from './User'
import { decryptoMsg } from '@/util/util.js'

class Message extends TableHelper {
  constructor () {
    super('message')
  }

  async getMsg (sessionId, limit = 100) {
    if (!sessionId) return null
    let objTable = await this.getObjTable()
    var lowerBound = [sessionId, 0]
    var upperBound = [sessionId, 999999999999999]
    let keyRangeValue = IDBKeyRange.bound(lowerBound, upperBound)
    let cursor = await objTable.index('session_id').openCursor(keyRangeValue, 'prev')
    let list = []
    let userIds = {}
    // let list2 = []
    while (cursor && cursor.value) {
      let value = cursor.value
      if (list.length < limit && value['session_id'] === sessionId) {
        if (value.msg_type == 4) {
          // 针对红包类型
          try {
            if (typeof value.msg === 'string') {
              value.msg = JSON.parse(decryptoMsg(value.msg))
            }
          } catch (ex) {
            console.error(ex)
          }
        } else {
          value.msg = decryptoMsg(value.msg)
        }

        list.unshift(value)
        userIds[value.from] = value.from
        if (value.to) {
          userIds[value.to] = value.to
        }

        cursor = await cursor.continue()
      } else {
        break
      }
    }

    let objUser = new User()
    let userMap = await objUser.getUserMap(userIds)

    return { list, userMap }
  }

  async updatePackInfo (hash, type, value) {
    let objTable = await this.getObjTable()
    let obj = await objTable.get(hash)
    obj.ext[type] = value
    objTable.put(obj)
  }
}

export default Message
