'use strict';

const parser = require('sax').parser;

function parse(data, config) {
  const res = [];
  const stack = [];
  let pointer = res;
  let trim = true;

  let strict = true;
  if (config && (config.strict !== undefined)) {
    strict = config.strict;
  }

  if (config !== undefined) {
    if (config.trim !== undefined) {
      trim = config.trim;
    }
  }

  const p = parser(strict);

  p.ontext = function (e) {
    if ((trim === false) || (e.trim() !== '')) {
      pointer.push(e);
    }
  };

  p.onopentag = function (e) {
    const leaf = [e.name, e.attributes];
    stack.push(pointer);
    pointer.push(leaf);
    pointer = leaf;
  };

  p.onclosetag = function () {
    pointer = stack.pop();
  };

  p.oncdata = function (e) {
    if ((trim === false) || (e.trim() !== '')) {
      pointer.push('<![CDATA[' + e + ']]>');
    }
  };

  p.write(data).close();
  return res[0];
}

module.exports = parse;
