import { openDb } from 'idb'

let objDb = null
class DB {
  static curDBUserId = localStorage.getItem('user_id');
  static async initDb () {
    let userId = localStorage.getItem('user_id')

    if (!objDb || DB.curDBUserId != userId) {
      // 切换用户
      if (DB.curDBUserId != userId) DB.curDBUserId = userId

      objDb = await initDb()
    }

    return objDb
  }
  static async init (tableName) {
    await DB.initDb()
    if (objDb) {
      return objDb.transaction(tableName, 'readwrite').objectStore(tableName)
    } else {
      return null
    }
  }
}

async function initDb () {
  let userId = DB.curDBUserId
  if (!userId) return null

  let dbName = `database_${userId}`
  let version = 3

  let objDb = await openDb(dbName, version, upgradeDB => {
    console.log(`oldVersion:${upgradeDB.oldVersion}, version:${version}`)
    // Note: we don't use 'break' in this switch statement,
    // the fall-through behaviour is what we want.
    switch (upgradeDB.oldVersion) {
      case 0:
        let objMessage = upgradeDB.createObjectStore('message', { keyPath: 'hash' })
        objMessage.createIndex('group_id', 'group_id', { unique: false })
        objMessage.createIndex('msg_num', 'msg_num', { unique: false })
        objMessage.createIndex('create_time_int', 'create_time_int', { unique: false })

        let objUser = upgradeDB.createObjectStore('user', { keyPath: 'user_id' })
        objUser.createIndex('user_name', 'user_name', { unique: true })
        objUser.createIndex('nick_name', 'nick_name', { unique: false })
        objUser.createIndex('is_admin', 'is_admin', { unique: false })
        objUser.createIndex('is_block', 'is_block', { unique: false })
        // falls through
      case 1:
        let objSession = upgradeDB.createObjectStore('session', { keyPath: 'session_id' })
        objSession.createIndex('pin_time_int', ['pin_time_int', 'update_time_int'], { unique: false })
        objSession.createIndex('is_pin', 'is_pin', { unique: false })
        objSession.createIndex('update_time_int', 'update_time_int', { unique: false })
        // falls through
      case 2:
        objMessage = upgradeDB.transaction.objectStore('message')
        objMessage.deleteIndex('group_id')
        objMessage.createIndex('session_id', ['session_id', 'create_time_int'], { unique: false })
    }
  }).catch(function (ex) {
    console.error('initDb error:' + ex.message)
    // alert('initDb error:' + ex.message)
  })

  return objDb
}

export default DB
