import TableHelper from './lib/TableHelper'

class Session extends TableHelper {
  constructor () {
    super('session')
  }
  async getSortList () {
    let objTable = await this.getObjTable()
    if (!objTable) return []

    let cursor = await objTable.index('pin_time_int').openCursor(null, 'prev')
    let list = []
    // let list2 = []
    while (cursor && cursor.value) {
      let value = cursor.value
      // 跳过已经删除的会话
      if (!value.delete_time_int || value.delete_time_int < value.update_time_int) {
        list.push(value)
      }

      cursor = await cursor.continue()
    }
    return list
  }
  async updateItem (sessionId, newData) {
    this.updateObject(newData, {
      session_id: sessionId
    })
  }
  async setUnread (sessionId, unreadNum) {
    this.updateItem(sessionId, {
      unread: unreadNum
    })
  }
  async setPin (sessionId, isPin) {
    let pinTime = isPin ? (new Date()).getTime() : 0
    this.updateItem(sessionId, {
      is_pin: isPin,
      pin_time_int: pinTime
    })
  }
  async setMute (sessionId, isMute) {
    this.updateItem(sessionId, {
      is_mute: isMute
    })
  }
  async clearData () {
    let objTable = await this.getObjTable()
    if (!objTable) return

    let cursor = await objTable.openCursor(null, 'prev')
    // let list2 = []
    while (cursor && cursor.value) {
      let value = cursor.value
      // 跳过已经删除的会话
      if (!value.delete_time_int) {
        objTable.delete(value.session_id)
      } else {
        // console.log('skip session_id:' + value.session_id)
      }

      cursor = await cursor.continue()
    }
  }
  async replaceSession (list) {
    let objTable = await this.getObjTable()
    if (!objTable) return list

    // 要合并已经被删除的会话
    for (let key in list) {
      let sessionId = list[key]['session_id']
      if (await objTable.get(sessionId)) {
        this.updateObject(list[key], { session_id: sessionId })
      } else {
        objTable.put(list[key])
      }
    }

    return this.getSortList()
  }
  async remove (sessionId) {
    let objTable = await this.getObjTable()
    if (!objTable) return

    // objTable.delete(sessionId)
    let item = await objTable.get(sessionId)
    if (item) {
      this.updateItem(sessionId, {
        delete_time_int: item.update_time_int
      })
    }
  }
  async recover (sessionId) {
    this.updateItem(sessionId, {
      delete_time_int: 0
    })
  }
}

export default Session
