import DB from './DB'

class TableHelper {
  constructor (tableName) {
    this.tableName = tableName
  }
  async getObjTable () {
    return DB.init(this.tableName)
  }
  async replaceObject (obj) {
    let objTable = await this.getObjTable()
    if (!objTable) return
    objTable.put(obj)
  }
  async replaceObjects (list) {
    let objTable = await this.getObjTable()
    if (!objTable) return
    // 解密数据
    for (let key in list) {
      objTable.put(list[key])
    }
  }
  async updateObject (newObject, where) {
    let objTable = await this.getObjTable()
    if (!objTable) return

    for (let key in where) {
      let obj = null
      if (key == objTable.keyPath) {
        obj = await objTable.get(where[key])
      } else {
        obj = await objTable.index(key).get(where[key])
      }

      if (obj) {
        obj = Object.assign(obj, newObject)
        objTable.put(obj)
      }

      break
    }
  }
}

export default TableHelper
