var sax = require('sax');

function parseXML(str, cb) {

  var obj, current, parser = sax.parser(true, { trim: true, lowercase: true })
  parser.onerror = parser.onend = done;

  function start() {
    try {
      parser.write(str).close()
    } catch(e) {
      done(e)
    }
  }

  function done(err) {
    cb(err, obj)
    done = function() { };
  }

  function newElement(name, attributes) {
    return {
      name: name || '',
      text: '',
      attributes: attributes || {},
      children: []
    }
  }

/*
  function toAttribute(parent, element) {
    if (typeof parent[element.name] === 'undefined')
      return parent[element.name] = element

    if (parent[element.name].constructor == Object)
      parent[element.name] = [parent[element.name]]

    parent[element.name].push(element)
  }
*/

  parser.ontext = function(t) {
    if (current) current.text += t
  }

  parser.onopentag = function(node) {
    var element = newElement(node.name, node.attributes)
    if (current) {
      element.parent = current
      current.children.push(element)
      // toAttribute(current, element)
    } else {
      obj = element
    }

    current = element
  };

  parser.onclosetag = function() {
    if (typeof current.parent !== 'undefined') {
      var just_closed = current
      current = current.parent
      delete just_closed.parent
    }
  }

  start()
}


