package basic;

import java.sql.*;
import java.io.*;
import uk.ac.ic.doc.automed.*;
import uk.ac.ic.doc.automed.modelmanagement.modeldef.SQLModelDef;
import uk.ac.ic.doc.automed.reps.*;
import uk.ac.ic.doc.automed.wrappers.*;

/*
 * An application to wrap the five versions of the University
 * database held in the sql92 datamodel.
 */
public class UniversityDatabaseWrapping {
  static String username="lab";
  static String password="lab";
  static String driver="com.microsoft.jdbc.sqlserver.SQLServerDriver";
  // static String driver="org.postgresql.Driver";
  static String urlbase="jdbc:microsoft:sqlserver://sqlserver.doc.ic.ac.uk\\;databaseName="; 
  // static String urlbase="jdbc:postgresql://localhost/";
  static String cfgFile=null;
  
  //static int features = SQLModelDef.PRIMARY_KEY +
  //  SQLModelDef.FOREIGN_KEY; //+ SQLWrapperFactory.DATA_TYPE;  //2 + 4 + 16
  static int features = SQLModelDef.PRIMARY_KEY +
    SQLModelDef.FOREIGN_KEY+SQLModelDef.DATA_TYPE;  //2 + 4 + 16
  
  static Model sql92=null;
  static Construct table=null;
  static Construct column=null;
  static Construct pk=null;
  static Construct fk=null;
  static SQLWrapperFactory wf;
  static boolean extra=false;
  static String schemaChoice=null;
  public static final String GLOBAL_SCHEMA_NAME="university";
  
  static void printHelp() {
    System.out.println("Usage: UniversityDatabaseWrapping [ options ]\n"+
      "  -debug <0-10>         set debug level\n" +
      "  -url <dbURL>          URL where DB located\n" +
      "  -driver <jdbcDriverClass>\n" +
      "  -user <user>\n"+
      "  -schema <schema name>\n"+
      "  -cfg <path_to_automed_ds_cfg>\n"+
      "  -password <password>\n" +
      "  -features <number>\n");
  }
  
  public static void readArgs(String[] args) {
    int i=0;
    
    try {
      while (i<args.length) {
        if (args[i].charAt(0)!='-') {
          System.out.println("Error at "+args[i]+"\n");
          printHelp();
          System.exit(0);
        } else if (args[i].startsWith("-debug"))
          STR.setDebugLevel(Integer.parseInt(args[++i]));
        else if (args[i].startsWith("-url"))
          urlbase=args[++i];
        else if (args[i].startsWith("-cfg"))
          cfgFile=args[++i];
        else if (args[i].startsWith("-help")) {
          printHelp();
          System.exit(0);
        } else if (args[i].startsWith("-driver"))
          driver=args[++i];
        else if (args[i].startsWith("-user"))
          username=args[++i];
        else if (args[i].startsWith("-schema"))
          schemaChoice=args[++i];
        else if (args[i].startsWith("-password"))
          password=args[++i];
        else if (args[i].startsWith("-features"))
          features=Integer.parseInt(args[++i]);
        
        ++i;
      }
      
      if (STR.atDebugLevel(5))
        System.out.println("Finished reading arguments, "+
          "about to read database");
      
      if (cfgFile!=null)
	DSRConfiguration.setDefaultConfigFileName(cfgFile);
      
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("You didn't supply an argument to the "
        +args[i-1]+" option!");
      printHelp();
      System.exit(0);
    }
  }
  
  private static void close() {
    try {
      DSR.close();
    } catch (DSRException ex) {
      ex.printStackTrace();
    }
  }

  public static void main(String[] args) {
    readArgs(args);
    
    try {
      System.out.println("AutoMed Repository: "+
        "Wrapping of University Databases");
      
      // Use a common wrapper factory to wrap a set of sources that
      // are to be integrated, so that they have a consistent modelling
      // langauge.
      wf=new SQLWrapperFactory();
      wf.getModelDefinition().setFeatures(features);
//      wf.setFeatures(SQLWrapperFactory.FOREIGN_KEY);
//      wf.setFeatures(SQLWrapperFactory.DATA_TYPE);
      //wf.setFeatures(SQLWrapperFactory.DATA_SIZE);
//      wf.setFeatures(SQLWrapperFactory.NULL_CONSTRAINT);
      
      if (Schema.exists(GLOBAL_SCHEMA_NAME))
	Schema.getSchema(GLOBAL_SCHEMA_NAME).retract();


      if (schemaChoice==null || "uni_s1".equals(schemaChoice))
	AutoMedInANutshell.wrapSchema(username,password,driver,
          urlbase,wf,
          "university1","uni_s1");
      if (schemaChoice==null || "uni_s2".equals(schemaChoice))
        AutoMedInANutshell.wrapSchema(username,password,driver,
          urlbase,wf,
          "university2","uni_s2");
      if (schemaChoice==null || "uni_s3".equals(schemaChoice))
        AutoMedInANutshell.wrapSchema(username,password,driver,
          urlbase,wf,
          "university3","uni_s3");
      //if (schemaChoice==null || "uni_s4".equals(schemaChoice))
      //  AutoMedInANutshell.wrapSchema(username,password,driver,
      //    urlbase,wf,
      //   "university4","uni_s4");
      //if (schemaChoice==null || "uni_s5".equals(schemaChoice))
      //  AutoMedInANutshell.wrapSchema(username,password,driver,
      //    urlbase,wf,
      //    "university5","uni_s5");
//      Schema[] su=s1.match(s2);
//      banner(su[0]);
//      su[0].listSchema();
      
      //TransformationPathway.findShortestPath(s1,su).write();
      //TransformationPathway.findShortestPath(s4,su).write();
      
      //if (su!=null) return;
      
      sql92=wf.getAutoMedModel();
      table=sql92.getConstruct(SQLModelDef.AUTOMED_SQL_MODEL_TABLE);
      column=sql92.getConstruct(SQLModelDef.AUTOMED_SQL_MODEL_COLUMN);
      if (wf.getModelDefinition().isFeatureInUse(SQLModelDef.PRIMARY_KEY))
        pk=sql92.getConstruct(SQLModelDef.AUTOMED_SQL_MODEL_PRIMARY_KEY);
      if (wf.getModelDefinition().isFeatureInUse(SQLModelDef.FOREIGN_KEY))
        fk=sql92.getConstruct(SQLModelDef.AUTOMED_SQL_MODEL_FOREIGN_KEY);
    } catch (SQLException se) {
      se.printStackTrace();
    } catch (IOException ie) {
      ie.printStackTrace();
    } catch (AutoMedException ame) {
      ame.printStackTrace();
    } catch (Throwable t) {
      System.err.println(t.toString());
      t.printStackTrace();
    } finally {
      close();
      System.exit(0);
    }
    
  }
}
