#include <sqlite3.h>
#include <vcclr.h>

bool print_result(array<Oblaat::NVPair^>^ results) {
  for each ( Oblaat::NVPair^ result in results ) {
    System::Console::Write("{0} = [{1}] ", result->name, result->value);
  }
  System::Console::WriteLine();
  return true;
}

int run() {

  Oblaat::SQLite3^ db = gcnew Oblaat::SQLite3();
  if ( db->open() != Oblaat::SQLite3::Result::OK ) {
    System::Console::WriteLine("Error : Can't open database : {0}", db->errmsg());
    return 1;
  }

  array<System::String^>^ statements = {
    "CREATE TABLE item (id INTEGER PRIMARY KEY, name TEXT NOT NULL, price REAL NOT NULL)", 
    "INSERT INTO item VALUES ( 1, 'ばなな', 123)", 
    "INSERT INTO item VALUES ( 2, 'りんご', 234)", 
    "INSERT INTO item VALUES ( 3, 'みかん', 345)", 
    "INSERT INTO item VALUES ( 4, 'なし',   456)", 
    "INSERT INTO item VALUES ( 5, 'もも',   567)", 
    "INSERT INTO item VALUES ( 6, 'びわ',   789)", 
    "INSERT INTO item VALUES ( 7, 'くり',   891)",

    "CREATE TABLE sales (id INTEGER PRIMARY KEY, quantity NOT NULL )", 
    "INSERT INTO sales VALUES ( 1, 6 )",
    "INSERT INTO sales VALUES ( 3, 4 )",
    "INSERT INTO sales VALUES ( 5, 2 )",

    "SELECT item.id, name, price, quantity, price*quantity FROM item, sales WHERE item.id = sales.id ORDER BY price*quantity",

    "CREATE VIEW named_sales AS SELECT name, quantity FROM sales, item WHERE item.id = sales.id",
    "SELECT * FROM named_sales"
  };

  for each ( System::String^ statement in statements ) {
    System::Console::WriteLine(statement);
    if ( db->exec(statement, gcnew Oblaat::Callback(print_result)) != Oblaat::SQLite3::Result::OK ) {
      return 1;
    }
  }

  return 0;
}

int main() {
  int result = 0;
  try {
    result = run();
  } catch ( Oblaat::SQLiteException^ ex ) {
    System::Console::WriteLine(ex->Message);
  }
  return result;
}
struct sqlite3 {};
