package io.vertx.example.rxjava.database.jdbc;

import io.vertx.core.json.JsonObject;
import io.vertx.example.util.Runner;
import io.vertx.ext.sql.ResultSet;
import io.vertx.rxjava.core.AbstractVerticle;
import io.vertx.rxjava.ext.jdbc.JDBCClient;
import io.vertx.rxjava.ext.sql.SQLConnection;
import rx.Observable;

/*
 * @author <a href="mailto:julien@julienviet.com">Julien Viet</a>
 */
public class Client extends AbstractVerticle {

  // Convenience method so you can run it in your IDE
  public static void main(String[] args) {
    Runner.runExample(Client.class);
  }

  @Override
  public void start() throws Exception {

    JsonObject config = new JsonObject().put("url", "jdbc:hsqldb:mem:test?shutdown=true")
                                        .put("driver_class", "org.hsqldb.jdbcDriver");

    JDBCClient jdbc = JDBCClient.createShared(vertx, config);

    // Connect to the database

    jdbc.getConnection(res -> {
      if (res.succeeded()) {
        SQLConnection conn = res.result();

        // Now chain some statements using flatmap composition
        Observable<ResultSet> resa = conn.updateObservable("CREATE TABLE test(col VARCHAR(20))").
          flatMap(result -> conn.updateObservable("INSERT INTO test (col) VALUES ('val1')")).
          flatMap(result -> conn.updateObservable("INSERT INTO test (col) VALUES ('val2')")).
          flatMap(result -> conn.queryObservable("SELECT * FROM test"));

        // Subscribe to the final result
        resa.subscribe(resultSet -> {
          System.out.println("Results : " + resultSet.getRows());
        }, err -> {
          System.out.println("Database problem");
          err.printStackTrace();
        });
      } else {
        res.cause().printStackTrace();
      }
    });


  }
}

@@ -718,40 +718,8 @@
 e%22)%0A
-                                
     
@@ -864,17 +864,16 @@
 atabase%0A
-%0A
     jdbc
@@ -890,89 +890,49 @@
 tion
-(res -%3E %7B%0A      if (res.succeeded()) %7B%0A        SQLConnection conn = res.result();
+Observable().subscribe(%0A        conn -%3E %7B
 %0A%0A  
@@ -937,16 +937,18 @@
         
+  
 // Now c
@@ -994,16 +994,18 @@
 osition%0A
+  
         
@@ -1096,32 +1096,36 @@
 ))%22).%0A          
+ 
+   
 flatMap(result -
@@ -1194,32 +1194,36 @@
 )%22)).%0A          
+  
+  
 flatMap(result -
@@ -1286,24 +1286,28 @@
 'val2')%22)).%0A
+    
           fl
@@ -1376,16 +1376,18 @@
         
+  
 // Subsc
@@ -1419,16 +1419,18 @@
         
+  
 resa.sub
@@ -1453,32 +1453,34 @@
  -%3E %7B%0A          
+ 
+ 
 System.out.print
@@ -1519,16 +1519,18 @@
 ows());%0A
+  
         
@@ -1543,32 +1543,34 @@
  -%3E %7B%0A          
+  
 System.out.print
@@ -1603,16 +1603,18 @@
         
+ 
+ 
 err.prin
@@ -1640,46 +1640,85 @@
     
+  
 %7D);%0A
+  
       %7D
- else %7B%0A        res.cause()
+,%0A%0A        // Could not connect%0A        err -%3E %7B%0A          err
 .pri
@@ -1743,20 +1743,20 @@
     
+  
 %7D%0A    
-%7D
 );%0A%0A
-%0A
   %7D%0A

Put back the Observable jdbc example