# 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 com.ziclix.python.sql import zxJDBC

def perform(con):
    c = con.cursor()
    c.execute('SELECT customer.id AS cid, name, phone, source ' + \
              'FROM customer JOIN customer_potential ON customer.id = customer_potential.id ' + \
              'ORDER BY cid')
    data = c.fetchall()
    c.close()
    for row in data:
        print('**future customer** %s, %s, %s' % (row[1], row[2], row[3]))
    c = con.cursor()
    c.execute('SELECT customer.id AS cid,name,address1,address2,phone,order_main.id AS oid,status,SUM(quantity*price) AS sumval ' + \
              'FROM customer JOIN customer_actual ON customer.id = customer_actual.id ' + \
              '              JOIN order_main ON customer.id = order_main.customer ' + \
              '              JOIN order_line ON order_main.id = order_line.order_main ' + \
              'GROUP BY customer.id,name,address1,address2,phone,order_main.id,status ' + \
              'ORDER BY cid, oid')
    data = c.fetchall()
    c.close()
    last_customer_id = 0
    for row in data:
        if row[0] != last_customer_id:
            print('%s, %s, %s, %s' % (row[1], row[2], row[3], row[4]))
            last_customer_id = row[0]
        print('  %s, %s, %.2f' % (row[5], row[6], row[7]))
    con.commit()
    con.close()
    
def performj(clznam, conurl, usr, pwd):
    print(conurl)
    perform(zxJDBC.connect(conurl, usr, pwd, clznam))

if len(argv) == 5:
    performj(argv[1], argv[2], argv[3], argv[4])
if len(argv) == 3:
    performj(argv[1], argv[2], None, None)
