import { CsvError, transform } from "./api/index.js";

const parse = function (data, opts = {}) {
  if (typeof data === "string") {
    data = Buffer.from(data);
  }
  const records = opts && opts.objname ? {} : [];
  const parser = transform(opts);
  const push = (record) => {
    if (parser.options.objname === undefined) records.push(record);
    else {
      records[record[0]] = record[1];
    }
  };
  const close = () => {};
  const error = parser.parse(data, true, push, close);
  if (error !== undefined) throw error;
  // 250606: `parser.parse` was implemented as 2 calls:
  // const err1 = parser.parse(data, false, push, close);
  // if (err1 !== undefined) throw err1;
  // const err2 = parser.parse(undefined, true, push, close);
  // if (err2 !== undefined) throw err2;
  return records;
};

// export default parse
export { parse };
export { CsvError };
