import TableHelper from './lib/TableHelper'
import User from './User'

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

  async getMsg (sessionId, limit = 30) {
    if (!sessionId) return null
    let objTable = await this.getObjTable()
    if (!objTable) return

    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) {
        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()
    if (!objTable) return

    let obj = await objTable.get(hash)
    if (obj) {
      obj.ext[type] = value
      objTable.put(obj)
    } else {
      console.log('can not find redpack:' + hash)
    }
  }

  async saveMsg (sessionId, data) {
    const objMessage = new Message()
    // 数据保存到indexDB
    let objTable = await objMessage.getObjTable()
    if (!objTable) return

    for (let key in data.list) {
      let value = Object.assign({ 'session_id': sessionId }, data.list[key])
      await objTable.put(value)
    }

    let objUser = new User()
    objUser.replaceObjects(data.userMap)
  }

  async removeMsg (sessionId, hash) {
    const objMessage = new Message()
    // 数据保存到indexDB
    let objTable = await objMessage.getObjTable()
    if (!objTable) return

    objTable.delete(hash)
  }
}

export default Message
