module Cardflex
  module Xml
    module Parser
      require 'rexml/document' unless defined? REXML::Document

      def self.xml_to_hash(xml)
        return {} if xml.nil?

        document = REXML::Document.new(xml)
        { _snakecase(document.root.name) => _parse_children(document.root) }
      end

      def self._parse_children(elem)
        if elem.has_elements?
          children = {}
          elem.each_element do |child|
            children[_snakecase(child.name)] = _parse_children(child)
          end
          children
        else
          elem.text
        end
      end

      def self._snakecase(key)
        key.tr('-', '_').to_sym
      end
    end
  end
end