# Collection of code snippets by Arne Vajhøj 
# (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
from sys import argv

from java.util.logging import Level
from java.util.logging import Logger

from javax.persistence import Persistence

import CustomerPotential
import CustomerActual

def perform(unit):
    print('%s:' % (unit))
    emf = Persistence.createEntityManagerFactory(unit)
    em = emf.createEntityManager()
    qp = em.createQuery('SELECT cp FROM CustomerPotential AS cp ORDER BY cp.id', CustomerPotential)
    resp = qp.getResultList();
    for cp in resp:
        print('**future customer** %s, %s, %s' % (cp.name, cp.phone, cp.source))
    qa = em.createQuery('SELECT DISTINCT ca FROM CustomerActual AS ca ' + \
                        'JOIN FETCH ca.orders o ' + \
                        'JOIN FETCH o.orderLines ol ' + \
                        'ORDER BY ca.id', CustomerActual)
    resa = qa.getResultList()
    for ca in resa:
        print('%s, %s, %s, %s' % (ca.name, ca.address1, ca.address2, ca.phone))
        for o in ca.orders:
            print('  %d, %s, %s' % (o.id, o.status, o.totalPrice))
    em.close()
    emf.close()
    
Logger.getLogger('org.hibernate').setLevel(Level.OFF)
if len(argv) == 2:
    perform(argv[1])
