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

class Sample {

  static bool print_result(object option, System.Array results) {
    foreach ( Oblaat.SQLite3.NVPair result in results ) {
      System.Console.Write("{0} = [{1}] ", result.name, result.value);
    }
    System.Console.WriteLine();
    return true;
  }

  public static void Main(string[] args) {

    Oblaat.SQLite3.Database db = new Oblaat.SQLite3.Database();
    if ( db.open() != Oblaat.SQLite3.Result.OK ) {
      System.Console.Error.WriteLine("Error : Can't open database : {0}", db.errmsg());
      return;
    }

    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, 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",
    };

    foreach ( string statement in statements ) {
      System.Console.WriteLine(statement);
      string errmsg;
      if ( db.exec(statement, Sample.print_result, null, out errmsg) != Oblaat.SQLite3.Result.OK ) {
        System.Console.Error.WriteLine("Error : {0}", errmsg);
        break;
      }
    }

    {
    Oblaat.SQLite3.Statement statement;
    db.prepare("INSERT INTO sales VALUES ( ?, ? )", out statement);
    statement.reset();
    statement.bind_int(1, 2);
    statement.bind_int(2, 5);
    statement.step();
    statement.reset();
    statement.bind_int(1, 4);
    statement.bind_int(2, 3);
    statement.step();
    statement.finalize();
    db.prepare("SELECT item.name, sales.quantity FROM item, sales WHERE item.id = sales.id", out statement);
    while ( statement.step() == Oblaat.SQLite3.Result.ROW ) {
      System.Console.WriteLine("{0} が {1}個 売れました", 
                               statement.column_text(0),
                               statement.column_int(1));
    }
    statement.finalize();
    }
    db.close();

  }

}
