'use strict';

var base = require('blockstore-core/base');
var raw = require('multiformats/codecs/raw');
var dagPB = require('@ipld/dag-pb');
var dagCBOR = require('@ipld/dag-cbor');
var sha2 = require('multiformats/hashes/sha2');
var toString = require('uint8arrays/to-string');

function _interopNamespace(e) {
  if (e && e.__esModule) return e;
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  }
  n["default"] = e;
  return Object.freeze(n);
}

var raw__namespace = /*#__PURE__*/_interopNamespace(raw);
var dagPB__namespace = /*#__PURE__*/_interopNamespace(dagPB);
var dagCBOR__namespace = /*#__PURE__*/_interopNamespace(dagCBOR);

const formats = {
  [raw__namespace.code]: raw__namespace.name,
  [dagPB__namespace.code]: dagPB__namespace.name,
  [dagCBOR__namespace.code]: dagCBOR__namespace.name
};
const hashes = { [sha2.sha256.code]: sha2.sha256.name };
class IPFSBlockstore extends base.BaseBlockstore {
  constructor(ipfs) {
    super();
    this.ipfs = ipfs;
  }
  async put(cid, buf) {
    const c = await this.ipfs.block.put(buf, {
      format: formats[cid.code],
      mhtype: hashes[cid.multihash.code],
      version: cid.version
    });
    if (toString.toString(c.multihash.bytes, 'base64') !== toString.toString(cid.multihash.bytes, 'base64')) {
      throw new Error('Multihashes of stored blocks did not match');
    }
  }
}
function createBlockstore(ipfs) {
  return new IPFSBlockstore(ipfs);
}

module.exports = createBlockstore;
