package nxm.database.lib;

import java.lang.reflect.Field;

/** Database Compatibility
    @author unknown
*/
public class Databaseable {
  protected String dbfields[] = null;

  /** default constructor */
  public Databaseable () {}

  /** Is the current instance database-compatible?
   *  @return true
   */
  public boolean isDatabaseable() {
    return (true);
  }

  /** Get the declared fields for Databaseable
   *  @return The names of the declared fields for Databaseable
   */
  public String[] getPublicFieldString() {
    Field myFields[] = getClass().getDeclaredFields();
    String retVal[] = new String[myFields.length];

    for (int i = 0; i < myFields.length; i++) {
      retVal[i] = myFields[i].getName();
    }

    return (retVal);
  }

  /** Gets the database fields as an array of strings
   *  @return the database fields as an array of strings
   */
  public String[] getDBFieldString() {
    String retVal[];

    if (dbfields == null) {
      retVal = getPublicFieldString();
    } else {
      retVal = dbfields;
    }

    return (retVal);
  }

  /** Gets the database fields as an array of Fields
   *  @return the database fields as an array of Fields
   */
  public Field[] getDBFields() {
   Field retVal[];

   if (dbfields == null) {
     retVal = getClass().getDeclaredFields();
   } else {
     try {
       Class<? extends Databaseable> myClass = getClass();
       retVal = new Field[dbfields.length];
       for (int i = 0; i < dbfields.length; i++) {
         retVal[i] = myClass.getDeclaredField(dbfields[i]);
       }
     } catch (Exception e) {
       System.out.println("Could not get DBFields: " + e);
       retVal = null;
     }
   }

   return (retVal);
  }

  /** Insert a query into a target database
   *  @param db    the target database
   *  @param table the table which contains values for the query
   *  @return status code 0
   */
  public int insertQuery(NxmDB db, String table) {
    String myFieldStr[] = getDBFieldString();

    if (myFieldStr.length < 1) return (0);

    StringBuffer qStr = new StringBuffer("INSERT INTO " + table + " (");
    for (int i = 0; i < myFieldStr.length; i++) {
      qStr.append(myFieldStr[i] + ",");
    }

    int len = qStr.length() - 1;
    qStr.replace(len, len, ")");
    qStr.append(" VALUES (");

    Field myFields[] = getDBFields();
    try {
      for (int i = 0; i < myFields.length; i++) {
        qStr.append(myFields[i].get(this) + ",");
      }
    } catch (Exception e) {
      System.out.println("Could not insert record: " + e);
      return(0);
    }
    len = qStr.length() - 1;
    qStr.replace(len, len, ")");

    System.out.println("The query looks like :\n" + qStr);

    return(0);
  }

}
