import { openDb } from 'idb'

let objDb = null

class DB {
  static async initDb (tableName) {
    if (!objDb) {
      objDb = await initDb()
      console.log('finish', objDb)
    }

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

async function initDb () {
  let userId = localStorage.getItem('user_id')
  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 })
    }
  })

  return objDb
}

export default DB
