// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class ListAfter5 {
    public static void main(String[] args) throws Exception {
        Class.forName("org.sqlite.JDBC");
        List<Order> res = new ArrayList<Order>();
        Connection con = DriverManager.getConnection("jdbc:sqlite:order.db");
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT myorder.id,myorder.customer,orderline.id,orderline.orderid,orderline.item,orderline.qty FROM myorder JOIN orderline ON myorder.id = orderline.orderid");
        int lastid = -1;
        Order lasto = null;
        while(rs.next()) {
            int id = rs.getInt(1);
            String customer = rs.getString(2);
            int lineid = rs.getInt(3);
            int orderid = rs.getInt(4);
            String item = rs.getString(5);
            int qty = rs.getInt(6);
            if(id != lastid) {
                lastid = id;
                lasto = new Order(id, customer);
                res.add(lasto);
            }
            OrderLine line = new OrderLine(lineid, orderid, item, qty);
            lasto.getLines().add(line);
        }
        rs.close();
        stmt.close();
        con.close();
        for(Order o : res) {
            System.out.printf("%d %s\n", o.getId(), o.getCustomer());
            for(OrderLine ol : o.getLines()) {
                System.out.printf("  %s : %d\n", ol.getItem(), ol.getQty());
            }
        }
    }
}
