const DB = {
  name: 'mapDB',
  version: 1,
  objName: 'mapAnimationData',
  fidName: 'fidsData'
}


function getDB () {
  return new Promise((resolve, reject) => {
    if (DB.db) {
      resolve(DB.db)
    } else {
      let request = indexedDB.open(DB.name, DB.version)
      
      request.onsuccess = e => {
        DB.db = e.target.result
        resolve(DB.db)
      }

      request.onerror = reject

      request.onupgradeneeded = e => {
        console.log(`${DB.name} versiton changed to ${DB.version}`)
        initDB(e.target.result)
      }
    }
  })
}

function close () {
  if (DB.db) {
    DB.db.close()
  }
}

function deleteDB () {
  indexedDB.deleteDatabase(DB.name)
}

function initDB (db) {
  let objectStore = db.createObjectStore(DB.objName, {
    keyPath: 'id',
    autoIncrement: true
  })
  
  objectStore.createIndex('id', 'id', {unique: true})
  objectStore.createIndex('type', 'type');
  objectStore.createIndex('features', 'features');

  objectStore = db.createObjectStore(DB.fidName, {
    keyPath: 'id',
    autoIncrement: true
  })
  objectStore.createIndex('fid', 'fids')
}

async function update (newItem, tab = DB.objName) {
  let request = (await getDB())
    .transaction([tab], "readwrite")
    .objectStore(tab)
    .put(newItem)

  return new Promise((resolve, reject) => {
    request.onsuccess = e => resolve(e.target.result)
    request.onerror = reject
  })
}

async function add (newItem, tab = DB.objName) {
  let request = (await getDB())
    .transaction([tab], "readwrite")
    .objectStore(tab)
    .add(newItem)
  
  return new Promise((resolve, reject) => {
    request.onsuccess = e => resolve(e.target.result)
    request.onerror = reject
  })
}

async function get(id, tab = DB.objName) {
  let request = (await getDB())
    .transaction([tab])
    .objectStore(tab)
    .get(id)

  return new Promise((resolve, reject) => {
    request.onsuccess = e => {
      if (request.result) {
        resolve(request.result)
      } else {
        resolve()
      }
    }

    request.onerror = e => {
      reject
    }
  })

}

async function clear(tab = DB.objName) {
  let request = (await getDB())
    .transaction([tab], 'readwrite')
    .objectStore(tab)
    .clear()

  return new Promise((resolve, reject) => {
    request.onsuccess = resolve
    request.onerror = reject
  })
}



clear(DB.fidName).then(resolve => {
  add({id: 1, fids: []}, DB.fidName)
})



export {
  get,
  add,
  update,
  clear
}