# Path: src/formpack/b64_attachment.py
# class B64Attachment(str):
#     """
#     * loaded from base64 string
#     * unloadable to file
#     """
# 
#     @classmethod
#     def _is_attachment(cls, data_uri):
#         return hasattr(data_uri, "startswith") and data_uri.startswith('data:')
# 
#     @classmethod
#     def _attachment_split(cls, data_uri):
#         """
#         accepts a data_uri,
#         returns a tuple (mediatype, extension, contents)
#         """
#         return re.match(DATA_URI_RE, data_uri).groups()
# 
#     @classmethod
#     def write_to_tempfile(cls, data_uri):
#         """
#         *placeholder method*
# 
#         this method will create a new TempFile (or cStringIO) with the
#         contents of the data_uri which can then be POST'ed to kobocat in
#         a mock submission.
#         """
#         (ftype, fext, fcont) = cls._attachment_split(data_uri)
#         fname = 'a%s.%s' % (randstr(10), fext)
#         return fname, '/tmp/path/to/%s' % fname
# 
# Path: src/formpack/utils/xform_tools.py
# def parse_xmljson_to_data(data, parent_tags=[], output=[]):
#     tag = data.get('tag')
#     new_parents = parent_tags + [tag]
#     if len(data.get('children', [])) > 0:
#         for child in data.get('children'):
#             parse_xmljson_to_data(child, new_parents, output)
#     else:
#         key = '/' + '/'.join(parent_tags) + '/' + tag
#         val = data.get('text')
#         output.append((key, val))
#     return output


import json
import re
from collections import OrderedDict
from io import StringIO
from lxml import etree
from pyquery import PyQuery
from .b64_attachment import B64Attachment
from .utils import parse_xmljson_to_data
                    _node.attr(key, struct['attributes'][key])
            if 'text' in struct:
                _node.text(struct['text'])
            elif 'children' in struct:
                for ugh, child in iter(struct['children'].items()):
                    _append_contents(child, _node)
            par.append(_node)

        _append_contents(contents, pqi)
        _xio = StringIO(pqi.html())
        _parsed = etree.parse(_xio)
        return etree.tostring(_parsed, pretty_print=True)

    @classmethod
    def from_abspaths(kls, par_item):
        items_ns = NestedStruct()
        for child in par_item.get('children'):
            tag = child.get('tag')
            layers = re.sub(r'^\/', '', tag).split('/')
            outer_layer = layers[-1]
            layers = layers[0:-1]
            cur_ptr = items_ns
            for _layer in layers:
                cur_ptr = cur_ptr.get(_layer)
                cur_ptr['tag'] = _layer
                cur_ptr = cur_ptr.get('children')
            cur_ptr[outer_layer] = {
                'tag': outer_layer,
                'text': child.get('children'),
            }

# Path: src/formpack/b64_attachment.py
# class B64Attachment(str):
#     """
#     * loaded from base64 string
#     * unloadable to file
#     """
# 
#     @classmethod
#     def _is_attachment(cls, data_uri):
#         return hasattr(data_uri, "startswith") and data_uri.startswith('data:')
# 
#     @classmethod
#     def _attachment_split(cls, data_uri):
#         """
#         accepts a data_uri,
#         returns a tuple (mediatype, extension, contents)
#         """
#         return re.match(DATA_URI_RE, data_uri).groups()
# 
#     @classmethod
#     def write_to_tempfile(cls, data_uri):
#         """
#         *placeholder method*
# 
#         this method will create a new TempFile (or cStringIO) with the
#         contents of the data_uri which can then be POST'ed to kobocat in
#         a mock submission.
#         """
#         (ftype, fext, fcont) = cls._attachment_split(data_uri)
#         fname = 'a%s.%s' % (randstr(10), fext)
#         return fname, '/tmp/path/to/%s' % fname
# 
# Path: src/formpack/utils/xform_tools.py
# def parse_xmljson_to_data(data, parent_tags=[], output=[]):
#     tag = data.get('tag')
#     new_parents = parent_tags + [tag]
#     if len(data.get('children', [])) > 0:
#         for child in data.get('children'):
#             parse_xmljson_to_data(child, new_parents, output)
#     else:
#         key = '/' + '/'.join(parent_tags) + '/' + tag
#         val = data.get('text')
#         output.append((key, val))
#     return output


# Path: src/formpack/submission.py
import json
import re
from collections import OrderedDict
from io import StringIO
from lxml import etree
from pyquery import PyQuery
from .b64_attachment import B64Attachment
from .utils import parse_xmljson_to_data

                    _node.attr(key, struct['attributes'][key])
            if 'text' in struct:
                _node.text(struct['text'])
            elif 'children' in struct:
                for ugh, child in iter(struct['children'].items()):
                    _append_contents(child, _node)
            par.append(_node)

        _append_contents(contents, pqi)
        _xio = StringIO(pqi.html())
        _parsed = etree.parse(_xio)
        return etree.tostring(_parsed, pretty_print=True)

    @classmethod
    def from_abspaths(kls, par_item):
        items_ns = NestedStruct()
        for child in par_item.get('children'):
            tag = child.get('tag')
            layers = re.sub(r'^\/', '', tag).split('/')
            outer_layer = layers[-1]
            layers = layers[0:-1]
            cur_ptr = items_ns
            for _layer in layers:
                cur_ptr = cur_ptr.get(_layer)
                cur_ptr['tag'] = _layer
                cur_ptr = cur_ptr.get('children')
            cur_ptr[outer_layer] = {
                'tag': outer_layer,
                'text': child.get('children'),
            }

        return items_ns