import sys

from . import structure, db, get
from .benchmark import benchmarking

def prod(a):
    benchmarking.start(sys.stderr)
    with db.begin_transaction(benchmark=False):
        a = unicode(a, 'utf-8')
        if '.' in a:
            rest, typ = a.rsplit('.', 1)
            typ = '.' + typ
        elif '>' in a:
            rest, typ = a.rsplit('>', 1)
        elif ':' in a:
            rest, typ = a.rsplit(':', 1)
        else:
            rest = a
            typ = u'txt'
        if '/' in rest:
            ename, prop_name = rest.split('/')
        else:
            ename = rest
            prop_name = u'product'
        with benchmarking('prodding %s.%s as %s' % (ename, prop_name, typ)):
            with benchmarking('getting element %s' % ename):
                e = structure.get_element(ename)
            if e is None:
                print >>sys.stderr, "No element %s exists!" % ename
                sys.exit(1)
            output = get.full_render(prop_name, typ, e, prop_name)
            sys.stdout.write(output)
            if not output.endswith('\n'):
                sys.stdout.write('\n')
