/* Collection of code snippets by Arne Vajhøj */
/* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "sqlite3.h"

#include "order.h"

int main()
{
    sqlite3 *con;
    sqlite3_stmt *sel;
    char *sqlstr = "SELECT myorder.id,myorder.customer,orderline.id,orderline.orderid,orderline.item,orderline.qty FROM myorder JOIN orderline ON myorder.id = orderline.orderid";
    int stat;
    int lastid;
    int count;
    struct order res[1000];
    int i, j;
    stat = sqlite3_open("order.db", &con);
    stat = sqlite3_prepare(con, sqlstr, strlen(sqlstr), &sel, NULL);
    lastid = -1;
    count = 0;
    while(sqlite3_step(sel) == SQLITE_ROW)
    {
        if(sqlite3_column_int(sel, 0) != lastid)
        {
            lastid = sqlite3_column_int(sel, 0);
            count++;
            res[count-1].id = sqlite3_column_int(sel, 0);
            strcpy(res[count-1].customer, (char *)sqlite3_column_text(sel, 1));
            res[count-1].nlines = 0;
        }
        res[count-1].line[res[count-1].nlines].id = sqlite3_column_int(sel, 2);
        res[count-1].line[res[count-1].nlines].orderid = sqlite3_column_int(sel, 3);
        strcpy(res[count-1].line[res[count-1].nlines].item, (char *)sqlite3_column_text(sel, 4));
        res[count-1].line[res[count-1].nlines].qty = sqlite3_column_int(sel, 5);
        res[count-1].nlines++;
    }
    sqlite3_finalize(sel);
    sqlite3_close(con);
    for(i = 0; i < count; i++)
    {
        printf("%d %s\n", res[i].id, res[i].customer);
        for(j = 0; j < res[i].nlines; j++)
        {
            printf("  %s : %d\n", res[i].line[j].item, res[i].line[j].qty);
        }
    }
    return 0;
}
