// SQLRetrieverThread6dF class
// Programmed by Alan Maxwell
//
// v1.00: 03 Oct 2002
//   Initial Release
//
// Synopsis
// --------
// This class is a subclass of SQLRetrieverThread that includes some specific
// formatting and HTML additions and functionality relating to the 6dF project.
//
// See SQLRetrieverThread for more details...
//

package net.alanmaxwell.sql;

import java.sql.*;

import net.alanmaxwell.sql.SQLDataFormatter;
import net.alanmaxwell.sql.SQLDataFormatterDecimal;
import net.alanmaxwell.sql.SQLDataFormatterSexagecimal;
import net.alanmaxwell.sql.SQLDataFormatterDate;

import net.alanmaxwell.html.HTMLStrings;

public class SQLRetrieverThread6dF extends SQLRetrieverThread
{
  private int specIdColumn = 0; // 0 = not searched; -1 = can't find, n = column
  private int targetNameColumn = 0; // 0 = not searched; -1 = can't find, n = column
  private int targetIdColumn = 0; // 0 = not searched; -1 = can't find, n = column

  protected boolean showHMS = true; // Should we use HMS for RA/DEC?

  public synchronized void setShowHMS(boolean status) {
    showHMS = status;
  };

  public synchronized boolean getShowHMS() {
    return showHMS;
  };


  protected boolean linkTAR = false;

  public synchronized void setLinkTAR(boolean status) {
    linkTAR = status;
  };

  public synchronized boolean getLinkTAR() {
    return linkTAR;
  };


  protected String linkEMAIL = "";

  public synchronized void setLinkEMAIL(String newEmail) {
    linkEMAIL = newEmail;
  };

  public synchronized String getLinkEMAIL() {
    return linkEMAIL;
  };


  public SQLRetrieverThread6dF(SQLServerInfoJDBC dbInfo)
  {
    super(dbInfo);
  }; // END of SQLRetrieverThread6dF(SQLServerInfoJDBC);

  protected String getPreTableHTML()
  {
    return "";
    /*
      "    <p> \n" +
      "      <small> \n" +
      "        NOTE: If your results contain the columns 'targetname' or 'specid' \n" +
      "        you will see 'Show' appear as a link towards the left edge of the table. \n" +
      "        This link opens a new browser window and displays any related object \n" +
      "        images and/or spectra - subsequently displayed images/spectra should appear \n" +
      "        in the same window.\n" +
      "      </small> \n" +
      "    </p>";
      */
  };

  protected void verifyQueryAndOptions() throws Exception
  {
    if (getLinkTAR() == true)
    {
      boolean searchingTargetName = true;

      int column = 1;
      while (
              (searchingTargetName) &&
              (column <= resultsNumColumns)
            )
      {
        if (columnNames[column-1].equalsIgnoreCase("TARGETNAME"))
        {
          searchingTargetName = false;
        }

        column++;
      }

      if (searchingTargetName)
      {
        throw new Exception(
          "A TAR file was requested with the 'tar=yes' option " +
          "but the query results do not contain the column 'targetname' so " +
          "the request cannot be completed. Please include the 'targetname' " +
          "column from any table if you wish to obtain a TAR file."
        );
      }
    };
  };

  protected String getPostTableHTML()
  {
    if (getLinkTAR() == true)
    {
      StringBuffer tempStringBuffer = new StringBuffer("");

      tempStringBuffer.append(
        "    <p> \n" +
        "      <img src=\"" + getOutputBaseURL() + "images/icons/tar.gif\" " +
                   "alt=\"Tar icon\" /> \n" +
        "      <a href=\"http://www-wfau.roe.ac.uk/~6df/" +
                 "cgi-bin/tar.cgi?file=" + CSVFileName +
                 "&email=" + getLinkEMAIL() + "\" >" +
                 "Request a TAR archive</a>" +
        "      of all available FITS files relating to objects returned by your query. \n" +
        "      An e-mail will be sent to <i>" + getLinkEMAIL() + "</i> once your TAR file is ready. \n " +
//        "      <br /> \n" +
        "      (Estimated size of the TAR is "
      );

      double TARFileEstimate = row * 200000.0;

      if (TARFileEstimate > 1000000)
      {
        tempStringBuffer.append(
          HTMLStrings.numbersTo1DP.format(TARFileEstimate/1024.0/1024.0) +
          " MB). \n"
        );
      }
      else if (TARFileEstimate > 1000)
      {
        tempStringBuffer.append(
          HTMLStrings.numbersTo1DP.format(TARFileEstimate/1024.0) +
          " KB). \n"
        );
      }
      else
      {
        tempStringBuffer.append(TARFileEstimate + " bytes). \n");
      };


       tempStringBuffer.append(
        "    </p> \n\n" +
        "    <p> \n" +
        "      NOTE: Please do not request TAR files when your CSV file \n" +
        "      contains more than 1000 rows <br /> \n" +
        "      (this is due to the probable large size of the resultant TAR file). \n" +
        "    </p> \n\n"
      );

      return
        super.getPostTableHTML() +
        tempStringBuffer.toString();
    }

    return super.getPostTableHTML();
  };

  protected String getInsertedTableCellsHeaderHTML()
  {
    // Reset these for the new query...
    specIdColumn = 0;
    targetNameColumn = 0;
    targetIdColumn = 0;

    return
      "        <th>&nbsp;</th> \n" +
      "        <th>&nbsp;</th> \n";
  };

  protected String getInsertedTableCellsDataHTML()
  {
    StringBuffer resultString = new StringBuffer("");
    String specid = "-1";
    String targetname = "-1";
    String targetid = "-1";

    // See if 'TARGETNAME' and/or 'SPECID' are in the returned results...

    // If we've not already discovered the columns we're after...
    if (targetNameColumn == 0) // Any one of the three would do here...
    {
      targetNameColumn = -1; // Assume it can't be found unless below...
      specIdColumn = -1;
      targetIdColumn = -1;

      for (int column = 1; column <= resultsNumColumns ; column++)
      {
        if ( (targetNameColumn < 0) &&
             (columnNames[column - 1].equalsIgnoreCase("TARGETNAME")) )
        {
          targetNameColumn = column;
        };

        if ( (specIdColumn < 0) &&
             (columnNames[column - 1].equalsIgnoreCase("SPECID")) )
        {
          specIdColumn = column;
        };

        if ( (targetIdColumn < 0) &&
             (columnNames[column - 1].equalsIgnoreCase("TARGETID")) )
        {
          targetIdColumn = column;
        };
      };
    };

    if (targetNameColumn > 0)
    {
      try
      {
      	targetname = results.getString(targetNameColumn);
      }
      catch (SQLException se)
      {
        targetname = "-1";
      }
    }

    if (specIdColumn > 0)
    {
      try
      {
      	specid = results.getString(specIdColumn);
      }
      catch (SQLException se)
      {
        specid = "-1";
      }
    }

    if (targetIdColumn > 0)
    {
      try
      {
      	targetid = results.getString(targetIdColumn);
      }
      catch (SQLException se)
      {
        targetid = "-1";
      }
    }

    resultString.append(
      "        <td nowrap=\"nowrap\" class=\"RowHeader\" bgcolor=\"" +
      getHTMLTableColorRowHeader() + "\"><b>" + row + "</b></td> \n"
    );

    if ((targetNameColumn > 0) || (specIdColumn > 0))
    {
      resultString.append(
        "        <td nowrap=\"nowrap\" class=\"RowHeader\" bgcolor=\"" +
        getHTMLTableColorRowHeader() + "\"> \n" +
        "          <a href=\"" + getOutputBaseURL() + "cgi-bin/show.cgi?" +
        "name=" + targetname +
        "&tid=" + targetid +
        "&specid=" + specid +
        "\" target=\"Show\">Show</a> \n" +
        "        </td> \n"
      );
    }
    else
    {
      resultString.append(
        "        <td nowrap=\"nowrap\" class=\"RowHeader\" bgcolor=\"" +
        getHTMLTableColorRowHeader() + "\">&nbsp;</td> \n"
      );
    }

    return resultString.toString();
  };

  // Override this method to allow us to specify different formatting for
  // different column types/data types...
  protected SQLDataFormatter getSQLDataFormatterForColumn(int column)
  {
    String colName = "";
    String colType = "";

    // Try to determine the column name and format it differently depending...
    try
    {
    	colName = resultsMetaData.getColumnName(column);
    }
    catch (SQLException e)
    {
      colName = "";
    };

    if
      (
        (colName.equalsIgnoreCase("RA")) ||
        (colName.equalsIgnoreCase("OBSRA")) ||
        (colName.equalsIgnoreCase("UP_RA"))
      )
    {
      if (getShowHMS())
      {
        return new SQLDataFormatterSexagecimal(true, 2);
      }
      else
      {
        return new SQLDataFormatterDecimal("0.0000000");
      }
    }
    else if
      (
        (colName.equalsIgnoreCase("DEC")) ||
        (colName.equalsIgnoreCase("OBSDEC")) ||
        (colName.equalsIgnoreCase("UP_DEC"))

      )
    {
      if (getShowHMS())
      {
        return new SQLDataFormatterSexagecimal(false, 1);
      }
      else
      {
        return new SQLDataFormatterDecimal("0.0000000");
      }
    }
    else if
      (
        (colName.equalsIgnoreCase("MATCH_DR"))
      )
    {
      return new SQLDataFormatterDecimal("0.0000");
    }
    else if
      (
//        (colName.equalsIgnoreCase("Z")) ||
        (colName.equalsIgnoreCase("Z_HELIO")) ||
        (colName.equalsIgnoreCase("Z_EMI")) ||
        (colName.equalsIgnoreCase("Z_ABS"))
      )
    {
      return new SQLDataFormatterDecimal("0.000000");
    }
    else if
      (
        (colName.equalsIgnoreCase("DISTANCE"))
      )
    {
      return new SQLDataFormatterDecimal("0.000");
    }
    else if
      (
        (colName.equalsIgnoreCase("UTDATE_V")) ||
        (colName.equalsIgnoreCase("UTDATE_R"))
      )
    {
      return new SQLDataFormatterDate();
    }


    // Try to determine the column type and format it differently depending...
    try
    {
      colType = resultsMetaData.getColumnTypeName(column);
    }
    catch (SQLException e)
    {
      colType = "";
    };

    if (colType.equalsIgnoreCase("float"))
    {
      return new SQLDataFormatterDecimal("0.000000");
    }
    else if (colType.equalsIgnoreCase("real"))
    {
      return new SQLDataFormatterDecimal("0.000");
    };

    return new SQLDataFormatter();
  };
};
