package test.nserverdemo;


import java.util.Properties;
import java.sql.SQLException;
import java.sql.DriverManager;
import java.io.*;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;



public class StartClient {
    
    public static final String DERBY_CLIENT_DRIVER = "org.apache.derby.jdbc.ClientDriver";
    private static int NETWORKSERVER_PORT=1621;
    
    // URL for the Derby client JDBC driver.
    private static final String DERBY_CLIENT_URL= "jdbc:derby://localhost:"+NETWORKSERVER_PORT+"/derbyDB;create=true;";
    
    // Default to using the Derby Client JDBC Driver for database connections
    String url = DERBY_CLIENT_URL;
    String jdbcDriver = DERBY_CLIENT_DRIVER;
    
    public void startSample() throws Exception {
        
        Connection conn = null;
        
        try  {
            System.setProperty("derby.system.home", "c:\\ESQueryProd");
            StartServer ss = new StartServer();
            ss.startSample();
            
            System.out.println("[StartClient] Sample Derby Network Server program demo starting. ");
            System.out.println("Please wait .....................");
            
            // Load the JDBC Driver
            try	{
                Class.forName(jdbcDriver).newInstance();
            } catch (Exception e) {
                System.out.println("[StartClient] Unable to load the JDBC driver. Following exception was thrown");
                e.printStackTrace();
                System.exit(1);  //critical error, so exit
            }
            Properties properties = new java.util.Properties();
            properties.setProperty("user","user1");
            properties.setProperty("password","user1");
            
            try	{
                conn =  (Connection) DriverManager.getConnection(url, properties);
            } catch(Exception e) {
                System.out.println("[StartClient] Connection request unsuccessful, exception thrown was: ");
                System.out.println("[StartClient] Please check if all the jar files are in the classpath and the dbUrl is set correctly.");
                e.printStackTrace();
                System.exit(1);  //critical error, so exit
            }
            
            Statement stx = conn.createStatement();
            try {
                stx.execute("CREATE TABLE FLAVIO (Campo1 char(50), Campo2 char(30))");
            } catch (Throwable t) {
                System.out.println("StartClient - errore in fase di creazione della tabella flavio "+t);
            }
            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(isr);
            
            try {
                while (true) {
                    System.out.println("StartClient - Premere invio per inserire due Records - Q per terminare... ");
                    String rec = br.readLine();
                    if (rec.length() != 0) {
                        if (rec.substring(0,1).equals("Q") || rec.substring(0,1).equals("q"))
                            break;
                    }
                    creaRec(stx);
                    leggiRec(stx);
                }
            } catch(Exception e) {
                System.out.println("StartClient - Errore nella richiesta "+e);
            }
            
            conn.close();
            System.out.println("[StartClient] End of Network server demo.");
            
            ss.chiudi();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void creaRec(Statement inSt) {
        try {
            java.util.Calendar cal = java.util.Calendar.getInstance();
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("HHmmss");
            String s = sdf.format(cal.getTime());
            inSt.execute("Insert into FLAVIO values('AA"+s+"', 'BB"+s+"')");
            inSt.execute("Insert into FLAVIO values('CC"+s+"', 'DD"+s+"')");
        } catch (Throwable t) {
            System.out.println("creaRec - errore - "+t);
        }
    }
    private void leggiRec(Statement inSt) {
        try {
            ResultSet rs = inSt.executeQuery("select * from FLAVIO");
            int ctr = 0;
            while (rs.next()) {
                System.out.println("Record letto = "+ctr+++" Campo1 = "+rs.getString(1).trim()+" Campo2 = "+rs.getString(2).trim());
            }
        } catch (Throwable t) {
            System.out.println("leggiRec - errore - "+t);
        }
    }
    public static void main(String[] args) {
        try {
            StartClient sc = new StartClient();
            sc.startSample();
        } catch (Throwable t) {
            System.out.println("TestSc - errore "+t);
        }
    }
}
