/*
 * オブラートに包んだくだもの屋さん (C++/CLI)
 */

using namespace Oblaat;

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

int main() {

  SQLite3::Database^ db = gcnew SQLite3::Database();
  if ( db->open() != SQLite3::Result::OK ) {
    System::Console::Error->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)", 

    "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 name, price, quantity, price*quantity FROM item, sales WHERE item.id = sales.id ORDER BY price*quantity",
  };

  for each ( System::String^ statement in statements ) {
    System::Console::WriteLine(statement);
    System::String^ errmsg = nullptr;
    if ( db->exec(statement, gcnew SQLite3::Callback(print_result), nullptr,  errmsg) != SQLite3::Result::OK ) {
      System::Console::Error->WriteLine("Error : {0}", errmsg);
      break;
    }
  }
  db->close();

  return 0;
}
