
import { bridgifyObject } from 'yaob'

import { asEdgeBox, wasEdgeBox } from '../../types/server-cleaners'

import { decrypt, decryptText, encrypt } from '../../util/crypto/crypto'
import { utf8 } from '../../util/encoding'

export function encryptDisklet(
  io,
  dataKey,
  disklet
) {
  const out = {
    delete(path) {
      return disklet.delete(path)
    },

    async getData(path) {
      const text = await disklet.getText(path)
      const box = asEdgeBox(JSON.parse(text))
      return decrypt(box, dataKey)
    },

    async getText(path) {
      const text = await disklet.getText(path)
      const box = asEdgeBox(JSON.parse(text))
      return decryptText(box, dataKey)
    },

    list(path) {
      return disklet.list(path)
    },

    setData(path, data) {
      return disklet.setText(
        path,
        JSON.stringify(wasEdgeBox(encrypt(io, Uint8Array.from(data), dataKey)))
      )
    },

    setText(path, text) {
      return this.setData(path, utf8.parse(text))
    }
  }
  bridgifyObject(out)
  return out
}
