// #include "ap_config.h"

#ifdef _WIN32
#include "windows.h"
#endif

#include <cstdio>
#include <cstdlib>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>

// #include <ctype.h>

// #include "setilib.h"
// #include "db_table.h"
// #include "sqlhdr.h"
// #include "schema_master.h"
// #include "seti_doppler.h"

#include "parse.h"
#include "xml_util.h"
#include "db_table.h"
#include "ap_schema.h"
// #include "astropulse.h"
#include "util.h"
#include "base64.h"
#include "ap_raw_data_db.h"
#undef read

#include <cstring>
#include <cassert>
#include <cstdlib>
#include <cstdio>
#include <cerrno>
#include <ctime>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

int main(int argc, char* argv[]) {

// Handle command line arguments

bool count = false;  // count how many pulses are in the appropriate time range
bool splitintobeams = false;  // plot 7 or 14? graphs vertically
bool linesdividingwus = false;  // show where wus begin and end
bool result = false;
bool workunit = false;
bool tape = false;
int timerangesec = 130;
double jdstart = 0;
double symsize = 1.0;
int picwidth = 640;
int picheight = 480;

char * db_name = "apb_db@sci_master_tcp";  // will change later if found in command line

bool have_where_clause = false;
char c_string[256];
std::string where_clause = "";

/* Possible arguments:
 *  -count	select count(*), the number of signals that fit the query
 *  -db_name	the name of the database we'll be connecting to.
 */
for (int i=1; i<argc; i++) {
    if (!strcmp(argv[i], "-count")) {
      count = true;
      fprintf(stderr, "counting signals instead of displaying<br>\n");
    }
    else if (!strcmp(argv[i], "-result")) {
      result = true;
      fprintf(stderr, "joining with result<br>\n");
    }
    else if (!strcmp(argv[i], "-workunit")) {
      workunit = true;
      fprintf(stderr, "joining with result, workunit<br>\n");
    }
    else if (!strcmp(argv[i], "-tape")) {
      tape = true;
      fprintf(stderr, "joining with result, workunit, tape<br>\n");
    }
    else if (!strcmp(argv[i], "-splitintobeams")) {
      splitintobeams = true;
      fprintf(stderr, "splitting into beams and pols<br>\n");
    }
    else if (!strcmp(argv[i], "-linesdividingwus")) {
      linesdividingwus = true;
      fprintf(stderr, "will include lines dividing wus<br>\n");
    }
    else if (!strncmp(argv[i], "-symsize", 8)) {
      symsize = atof(argv[i] + 8);
      fprintf(stderr, "symsize: %f<br>\n", symsize);
    }
    else if (!strncmp(argv[i], "-timerangesec", 13)) {
      timerangesec = atoi(argv[i] + 13);
      fprintf(stderr, "timerangesec: %d<br>\n", timerangesec);
    }
    else if(!strncmp(argv[i], "-jdstart", 8)) {
      jdstart = strtod(argv[i] + 8, NULL);
      fprintf(stderr, "jdstart: %f<br>\n", jdstart);
    }
    else if(!strncmp(argv[i], "-picwidth", 9)) {
      picwidth = atoi(argv[i] + 9);
      fprintf(stderr, "Picture width: %d<br>\n", picwidth);
    }
    else if(!strncmp(argv[i], "-picheight", 10)) {
      picheight = atoi(argv[i] + 10);
      fprintf(stderr, "Picture height: %d<br>\n", picheight);
    }
    else if (!strncmp(argv[i], "-db_name", 8)) {
      db_name = argv[i] + 8;
      fprintf(stderr, "Running with db %s<br>\n", db_name);
    }
    else {  // where clause
      if(have_where_clause) {
        fprintf(stderr, "In query_to_html : unexpected arg: %s  (Should only be a where clause.)  Usage: query_to_html where_clause [-splitintobeams] [-linesdividingwus] [-timerangesecN] -jdstartT [-picwidth] [-picheight] [-db_nameNAME]<br>\n", argv[i]);
        exit(-1);
      }
      where_clause = argv[i];      
      have_where_clause = true;
    }
}

if(have_where_clause == false) {
  printf("In time_range_to_html : no where clause.  Usage: query_to_html where_clause [-splitintobeams] [-linesdividingwus] [-timerangesecN] -jdstartT [-picwidth] [-picheight] [-db_nameNAME]<br>\n");
  exit(-1);
}

if(jdstart == 0) {
  printf("In time_range_to_html : no jdstart.  Usage: query_to_html where_clause [-splitintobeams] [-linesdividingwus] [-timerangesecN] -jdstartUT [-picwidth] [-picheight] [-db_nameNAME]<br>\n");
  exit(-1);
} 

double tmin, tmax;
tmin = jdstart;
tmax = jdstart + timerangesec / 1440.0 / 60.0;

FILE * time_range_sql = fopen("time_range.sql", "w");
if(!time_range_sql) {
  printf("In time_range_to_html.cpp : can't open file \"time_range.sql\" for write.\n");
  exit(-1);
}
fprintf(time_range_sql, "database %s;\n", db_name);
fprintf(time_range_sql, "unload to \"signal_list.txt\" delimiter \" \"\n");
fprintf(time_range_sql, "select \n");
fprintf(time_range_sql, "ap_signal.dm, (ap_signal.time - %f) as timeoffset, ap_signal.period", tmin);
if(splitintobeams) {
  fprintf(time_range_sql, ",\nsubstring(workunit.name from 14 for 1) as beam, \n");
  fprintf(time_range_sql, "substring(workunit.name from 17 for 1) as polarization \n");
} else
  fprintf(time_range_sql, "\n");
if(splitintobeams) {
  fprintf(time_range_sql, "from ap_signal, workunit, result \n");
  fprintf(time_range_sql, "where result.id = ap_signal.resultid and workunit.id = result.wuid and\n");
} else {
  fprintf(time_range_sql, "from ap_signal \n");
  fprintf(time_range_sql, "where \n");
}
fprintf(time_range_sql, "ap_signal.time > %f and time < %f and %s and\n", tmin, tmax, where_clause.c_str());
fprintf(time_range_sql, "ap_signal.raw_data is not null;");
fclose(time_range_sql);
 
setenv("INFORMIXDIR", "/disks/thumper/a/apps/informix", 1);
setenv("INFORMIXSQLHOSTS", "/disks/thumper/a/apps/informix/etc/sqlhosts", 1);
setenv("INFORMIXSERVER", "sci_master_tcp", 1);
setenv("IDL_PATH", ":~vonkorff/build/Josh_idl_files/analysis_July_08:+~/idl:+~korpela/idl:+/usr/local/rsi:+/home/korpela/NEWCVS/analysis/lib/idl_astro", 1);

// int retval = db_change(db_name);
// fprintf(stderr, "db_change(%s) returns %d\n", db_name, retval);

if(workunit || result || tape) {
  printf("In query_to_html : Joins with workunit and result are turned on by default.  No support for join with tape.<br>\n");
  exit(-1);
}

// Open the html file
char html_filename[256];
long create_time = time(NULL);
sprintf(html_filename, "time_range_%ld.html", create_time);
FILE * html_file = fopen(html_filename, "w");
if(!html_file) {
  printf("In time_range_to_html : error opening file %s for write.<br>\n", html_filename);
  exit(-1);
}

// Write to the html file
fprintf(html_file, "<html>\n");
fprintf(html_file, "<head>\n<title>");
fprintf(html_file, "Time range with jd start %f", jdstart);
fprintf(html_file, "</title>\n</head>\n<body>\n");

fprintf(html_file, "Time range with jd start %f<br>\n", jdstart);
fprintf(html_file, "time range %d seconds <br>\n where_clause = \"%s\" <br>\n", timerangesec, where_clause.c_str());
fprintf(html_file, "Extracted from database %s<br>\n<br>\n", db_name);

FILE * timerange_jpg;
FILE * timerange_txt;

char splitintobeamscstring[30];
if(splitintobeams) 
  sprintf(splitintobeamscstring, "/splitintobeams,");
else
  sprintf(splitintobeamscstring, "");

char symsizecstring[30];
sprintf(symsizecstring, "symsize=%f,", symsize);

FILE * time_range_idl_txt = fopen("time_range_idl.txt", "w");
if(!time_range_idl_txt) {
  printf("In time_range_to_html : error opening file time_range_idl.txt for write.<br>\n");
  exit(-1);
}
fprintf(time_range_idl_txt, "!PATH += \":~vonkorff/build/Josh_idl_files/analysis_July_08\"\n");
fprintf(time_range_idl_txt, ".run time_range.pro\n");
fprintf(time_range_idl_txt, "time_range, file=\"signal_list.txt\", xmin=%f, xmax=%f, dm_hi=15000, jpgname=\"plots/time_range.jpg\", %s %s /zbuffer\n", 0.0, (float) (tmax - tmin), splitintobeamscstring, symsizecstring);
fclose(time_range_idl_txt);

fprintf(stderr, "where_clause: %s\n", where_clause.c_str());

// Create signal_list.txt
if(system("/disks/thumper/a/apps/informix/bin/dbaccess -e < time_range.sql")) {
  printf("In time_range_to_html : error when running dbaccess\n");
  exit(-1);
}

FILE * signal_list_txt = fopen("signal_list.txt", "r");
if(!signal_list_txt) {
  printf("In time_range_to_html : can't open file signal_list.txt<br>\n");
  exit(-1);
}
fseek(signal_list_txt, 0, SEEK_END);
long numbytes = ftell(signal_list_txt);
printf("Number of bytes in signal_list.txt: %ld<br>\n", numbytes);
fclose(signal_list_txt);

if(numbytes == 0) {
  printf("<b>In time_range_to_html : no signals satisfy your criteria.</b><br>\n");
  exit(0);
}

// This is suppose to capture stderr from time_range_script, discard stdout .. not sure it was working
// if(system("sh -c '/disks/ptolemy/c/home/boincadm/public_html/waterfallscript 2>&1 1>/dev/null'"))  
// if(system("/disks/ptolemy/c/home/boincadm/public_html/waterfallscript 2>& /dev/null")) 
// if(system("/disks/ptolemy/c/home/boincadm/public_html/time_range_script > /dev/null")) {
if(system("/disks/ptolemy/c/home/boincadm/public_html/time_range_script")) {
  printf("In time_range_to_html : error when running time_range_script<br>\n");
  exit(-1);
}

int retval;
// mv time_range.jpg
FILE * time_range_jpg = fopen("plots/time_range.jpg", "r");
if(!time_range_jpg) {
  printf("In time_range_to_html : error opening file %s for read (need to move it.)<br>\n", "plots/time_range.jpg");
  exit(-1);
}
fclose(time_range_jpg);
char time_range_mv[256];
sprintf(time_range_mv, "mv plots/time_range.jpg plots/time_range_%f.jpg", jdstart);
fprintf(html_file, "<img src=\"plots/time_range_%f.jpg\" width=%d height=%d><br><br>\n", jdstart, picwidth, picheight);
retval = system(time_range_mv);
if(retval) {
  printf("In time_range_to_html : mv failed.<br>\n");
  exit(-1);
}

fprintf(html_file, "<body></html>\n");
fclose(html_file);

// Print a link to the html file
printf("<html>\n<head>\n");
printf("<meta http-equiv=\"REFRESH\" content=\"0;url=http://setiathome.ssl.berkeley.edu/~boincadm/%s\"", html_filename);
printf("</head>\n");

}
