'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var cid = require('multiformats/cid');
var configure = require('../lib/configure.js');
var multipartRequest = require('ipfs-core-utils/multipart-request');
var toUrlSearchParams = require('../lib/to-url-search-params.js');
var abortSignal = require('../lib/abort-signal.js');

const createPut = (codecs, options) => {
  const fn = configure.configure(api => {
    const put = async (dagNode, options = {}) => {
      const settings = {
        storeCodec: 'dag-cbor',
        hashAlg: 'sha2-256',
        ...options
      };
      let serialized;
      if (settings.inputCodec) {
        if (!(dagNode instanceof Uint8Array)) {
          throw new Error('Can only inputCodec on raw bytes that can be decoded');
        }
        serialized = dagNode;
      } else {
        const storeCodec = await codecs.getCodec(settings.storeCodec);
        serialized = storeCodec.encode(dagNode);
        settings.inputCodec = settings.storeCodec;
      }
      const controller = new AbortController();
      const signal = abortSignal.abortSignal(controller.signal, settings.signal);
      const res = await api.post('dag/put', {
        timeout: settings.timeout,
        signal,
        searchParams: toUrlSearchParams.toUrlSearchParams(settings),
        ...await multipartRequest.multipartRequest([serialized], controller, settings.headers)
      });
      const data = await res.json();
      return cid.CID.parse(data.Cid['/']);
    };
    return put;
  });
  return fn(options);
};

exports.createPut = createPut;
