<?php 

// A php program that generates a postage stamp request form

// There are two modes on the form List Images simply lists the input images that match
// the image selection critera

// When make stamps is selected when the page is posted, a postage stamp request is queued.
// 
// Then we respond to http posts by listing the status of the jobs.
// Once all of the jobs complete we set the page back to submission mode again
// The mode for the page is given by $request_id != 0

$COMMAND_DIR = "/export/data0/bills/src/ipp/pstamp/scripts";
//$STAMPS_DIR = "/export/data1/bills/pstamp/work/stamps";

// Initialize variables
$output_array = array();

$request_id = 0;
$last_request_id = 0;

$raw_selected = "";
$chip_selected = "";
$warp_selected = "";
$stack_selected = "";
$diff_selected = "";

$exp_checked = "";
$file_checked = "";
$coord_checked = "";
$list_checked = "";
$pstamp_checked = "";
$get_checked = "";

$command_line = "";
$error_line = "";
$command_status = "";

$outFileset = "";

// Initialize the request variables that we depend upon
$rvar_project="gpc1";

$rvar_user_tag="";
$rvar_select_by = "";
$rvar_img_type = "";
$rvar_id = "";
$rvar_class_id = "";
$rvar_cell_id = "";

$rvar_center_type = "";
$rvar_range_type  = "";

$rvar_RA = "";
$rvar_DEC = "";
$rvar_dRA = "";
$rvar_dDEC = "";
$rvar_X = "";
$rvar_Y = "";
$rvar_W = "";
$rvar_H = "";

$rvar_cmd_mode = "";
$rvar_last_cmd_mode = "";
$rvar_request_id = 0;
$rvar_last_request_id = 0;

// now get the values from this post

import_request_variables("gp", "rvar_");

// figure out which select_by is set and save it's checked value 

if ($rvar_select_by == "exposure_id") {
    $exp_checked = "CHECKED";
} else if ($rvar_select_by == "db_id") {
    $file_checked = "CHECKED";
} else if ($rvar_select_by == "coord") {
    $coord_checked = "CHECKED";
} else {
    // nothing checked default to By Exposure
    $exp_checked = "CHECKED";
}

// get the Image type
if ($rvar_img_type == "raw") {
    $raw_selected = "selected";
} else if ($rvar_img_type == "chip") {
    $chip_selected = "selected";
} else if ($rvar_img_type == "warp") {
    $warp_selected = "selected";
} else if ($rvar_img_type == "stack") {
    $stack_selected = "selected";
} else if ($rvar_img_type == "diff") {
    $diff_selected = "selected";
}

// is the center is specified in Pixels or sky coordinates
if ($rvar_center_type == "Sky") {
    $sky_checked="checked";
    $pix_checked="";
} else {
    $sky_checked="";
    $pix_checked="checked";
}

// is the range is specified in Pixels or sky coordinates
if ($rvar_range_type == "Sky") {
    $rsky_checked="checked";
    $rpix_checked="";
} else {
    $rpix_checked="checked";
    $rsky_checked="";
}

// When request_id is non-zero we respond to posts by check the status of that request
// request_id gets set to zero when the status of all jobs for the request is 'stop'
$request_id = $rvar_request_id;
$last_request_id = $rvar_last_request_id;

// during request the page doesn't have cmd_mode set. So we remember the lat real value
// and use that
if (!$rvar_cmd_mode) {
    $rvar_cmd_mode = "$rvar_last_cmd_mode";
}

if ($rvar_cmd_mode == "Make Stamps") {
    $pstamp_checked = "checked";
    $list_checked = "";
    $get_checked = "";
} else if ($rvar_cmd_mode == "Get Images") {
    $get_checked = "checked";
    $list_checked = "";
    $pstamp_checked = "";
} else {
    $list_checked = "checked";
    $get_checked = "";
    $pstamp_checked = "";
}


// echo "rvar_request_id: $rvar_request_id\n";

// HERE is the logic for running the various commands

// How do we know? Well if we aren't running the initial get of the web page?
// Well, in that case rvar_img_type is not set so key off of that
// TODO: find a better way to decide whether or not to run commands

if ($rvar_img_type) {

    $jobFinished = 0;
    if ($request_id == 0) {
        try {
            $command_line = build_request_cmd();
            $error_line = "";
            run_command($command_line);
            if (! $list_checked) {
                // The only output from a successful run is the request_id
                $request_id = Array_pop($output_array);
                $last_request_id = $request_id;
                setcookie("our_request_id", $request_id);
                // echo "The request id is $request_id\n";
                if (count($output_array) != 0) {
                    throw new Exception("unexpected output returned by pstampwebrequest.");
                }

                $jobRunning = getRequestStatus();
                if (!$jobRunning) {
                    $jobFinished = 1;
                    $request_id = 0;
                }

            }
        } catch (Exception $e) {
            $error_line = $e->getMessage();
        }
    } else {
        try {
            // get the list of jobs for the request
            // echo "calling getRequestStatus\n";
            $jobRunning = getRequestStatus();

            if (!$jobRunning) {
                $jobFinished = 1;
                $request_id = 0;
            }

        } catch (Exception $e) {
            echo "Got Exception $request_id $e\n";
            $error_line = $e->getMessage();
        }
    }
    if ($last_request_id) {
        // This doesn't work for get_image
        listJobs($last_request_id, $jobFinished);
    }
}

function build_request_cmd()
{
    global $rvar_project, $rvar_user_tag;
    global $sky_checked, $rsky_checked;
    global $list_checked;
    global $get_checked;
    global $rvar_RA, $rvar_DEC;
    global $rvar_dRA, $rvar_dDEC;
    global $rvar_X, $rvar_Y;
    global $rvar_W, $rvar_H;
    global $exp_checked, $file_checked, $coord_checked;
    global $rvar_img_type;
    global $rvar_id, $rvar_class_id;
    global $command_line;

    $cmd = "pstamp_runcommand.sh pstamp_webrequest.pl";

    $making_stamps = 1;
    
    if ($list_checked) {
        $cmd .= " -list";
        $making_stamps = 0;
    } else if ($get_checked) {
        $making_stamps = 0;
        $cmd .= " -get_image";
    }

    if (! $rvar_project ) {
        throw new Exception('project must be specified.');
    }
    $cmd .= " -project $rvar_project";

    if ($making_stamps) {
        if (!$rvar_user_tag) {
            throw new Exception('Stamp Name must be specified.');
        }
        $cmd .= " -user_tag $rvar_user_tag";
    }

    if ($making_stamps || $coord_checked) {
        // Set up the ROI parameters
        if ($sky_checked) {
            if (! $rvar_RA || ! $rvar_DEC) {
                throw new Exception('RA and DEC must be specified.');
            }
            $cmd .= " -skycenter $rvar_RA $rvar_DEC";
        } else {
            if (! $rvar_X || ! $rvar_Y) {
                throw new Exception('X and Y must be specified.');
            }
            $cmd .= " -pixcenter $rvar_X $rvar_Y";
        }

        if ($rsky_checked) {
            if (! $rvar_dRA || ! $rvar_dDEC) {
                throw new Exception('dRA and dDEC must be specified.');
            }
            $cmd .= " -arcrange $rvar_dRA $rvar_dDEC";
        } else {
            if (! $rvar_W || ! $rvar_H) {
                throw new Exception('width and height must be specified.');
            }
            $cmd .= " -pixrange $rvar_W $rvar_H";
        }
    }


    if (! $rvar_img_type) {
        // this actually can't happen
        throw new Exception('Must set image type.');
    }

    if ($exp_checked) {
        if (! $rvar_id ) {
            throw new Exception('Must set Exposure ID.');
        }
        $cmd .= " -byexp $rvar_img_type $rvar_id";
    } else if ($file_checked) {
        if (! $rvar_id ) {
            throw new Exception('Must set ID.');
        }
        $cmd .= " -byid $rvar_img_type $rvar_id";
    } else if ($coord_checked) {
        // $cmd .= " -bycoord $rvar_img_type";
        $coord_checked = "";
        $exp_checked = "checked";
        throw new Exception("Image selection by coordinate not implemented yet.");
    }

    if (($rvar_img_type == "raw") || ($rvar_img_type == "chip")) {
        if (! $rvar_class_id ) {
            throw new Exception("must specify Class ID with Image Type $rvar_img_type.");
        }
        $cmd .= " $rvar_class_id";
    }

    return escapeshellcmd($cmd);
}

function run_command($command_line)
{
    global $output_array;
    global $error_line;
    global $command_status;
    global $COMMAND_DIR;

    // echo "running $command_line\n";

    exec ("$COMMAND_DIR/$command_line", $output_array, $command_status);

    $size = sizeof($output_array);
    // echo "output_array  contains $size lines\n";
    if ($command_status == 0) {
        // On success we just remember the results
        $dump_results = 0;
        if ($dump_results) {
            echo "Output: $size lines\n";
            for ($i = 0; $i < $size; $i++) {
                echo "$output_array[$i]\n";
            }
        }
    } else {
        // copy the output to the error_line
        $error_line = "";
        for ($i = 0; $i < $size; $i++) {
             $error_line .= "$output_array[$i]\n";
        }
    }

}

function printURL($line)
{
    global $request_id;
    global $last_request_id;

    echo "<tr><td>";
    $doURL = 1;
    if ($doURL) {
        // echo "output_line: $line\n";
        $elements = explode(" ", $line);
        if (count($elements) == 3) {
            $job_id   = $elements[0];
            $state    = $elements[1];
            $path     = $elements[2];
            $fileName = basename($path);
            if ($state == "stop") {
                // this job is done, list the url as a link
                echo "<a href=\"http:$path\" target=\"_blank\" type=\"image/fits\">";
                echo $fileName;
                echo "</a>";
                echo "&nbsp;&nbsp;&nbsp; request_id: $last_request_id &nbsp;&nbsp;";
                echo "job_id: $job_id &nbsp;&nbsp;&nbsp; state: $state";
            } else {
                // TODO: refine this output
                echo "$fileName&nbsp;&nbsp;&nbsp; request_id: $request_id &nbsp;&nbsp;&nbsp;";
                echo "job_id: $job_id &nbsp;&nbsp;&nbsp; state: $state";
            }
        }
    } else {
        print "$line";
    }

    echo "</td></tr>";
}

function countRunningJobs()
{
    global $output_array;

    $runningJobs = 0;
    $size = sizeof($output_array);
    for ($i = 0; $i < $size; $i++) {
        $elements = explode(" ", $output_array[$i]);
        if (count($elements) == 3) {
            $state    = $elements[1];
            if ($state != "stop") {
                $runningJobs++;
            }
        } else {
            throw new Exception ("incorrect data in job status: $output_array[$i]");
        }
    }
    return $runningJobs;
}

function listJobs($request_id, $jobFinished)
{

    $command_line = "pstamp_runcommand.sh pstamp_listjobs.pl $request_id";
    run_command($command_line);
    if ($jobFinished) {
        global $outFileset;
        $parse_error = "/var/www/html/ds/dsroot/$outFileset/parse_error";
        #echo "reading $parse_error\n";
        // readfile( $parse_error );
        $fhandle = fopen($parse_error, "r");
        if ($fhandle) {
            $contents = fread($fhandle, 1024);
            if ($contents) {
                global $last_request_id;
                global $error_line;
                $error_line = "Request $last_request_id: $contents\n";
            }
        }
    }
}

function getRequestStatus()
{
    global $request_id;
    global $command_status;
    global $output_array;
    global $outFileset;

    $command_line = "pstamp_runcommand.sh pstamptool -listreq -req_id $request_id -simple";
    run_command($command_line);
    if ($command_status == 0) {
        $size = sizeof($output_array);
        $runningReq = 0;
        for ($i = 0; $i < $size; $i++) {
            $elements = explode(" ", $output_array[$i]);
            if (count($elements) >= 4) {
                $state = $elements[2];
                $outFileset = $elements[4];
                if ($state != "stop") {
                    $runningReq++;
                }
            } else {
                throw new Exception ("incorrect data in job status: $output_array[$i]");
            }
        }
        return $runningReq;
    } else {
        return 0;
    }
}

?>

<!-- Beginning of the HTML --------------------------------------------- -->
<html>
 <head>
  <title>Postage Stamp Request Form</title>
    <?php
        if ($request_id != 0) {
            // This doesn't do what I want. It does a get not a post

            // echo '<META HTTP-EQUIV="refresh" CONTENT="5">';

        }
    ?>
 </head>
<form method="post">

<body>

<H1 align=center>
Postage Stamp Request Form
</h1>

<!-- Whole page is a single column table -->


<table width=90% align=center>


<!-- first row in the main table is the image selector UI which consists of a 2 x 3 table -->
<tr>
<td>

<table width=100% align=center>

<!-- first row of image selector is "Project" pulldown menu "Select Image By" radio boxes -->
<tr>
<td width=20% >
  <table>
    <tr><td><b>Project:</b>&nbsp;&nbsp;&nbsp;</td>
        <td><select name="project">
            <option>gpc1
        </td>
    </tr>
  </table>

<td>
&nbsp;<b>Select Images By:</b>&nbsp;&nbsp;&nbsp;
<input type=radio name="select_by" value="exposure_id" <?php echo $exp_checked; ?> >Exposure ID
&nbsp;
<input type=radio name="select_by" value="db_id" <?php echo $file_checked; ?> >Database ID
&nbsp;
<!--
<input type=radio name="select_by" value="coord" <?php echo $coord_checked; ?> >Coordinates
-->
</td>
</tr>


<!-- the second row of the image selector table contains 
    "Image Type" pulldown menu   "ID:" text input "Class ID" text input
-->

<tr>
<td width=20%>
<table>
    <td><b>Image Type:</b>&nbsp;</td>
    <td>
        <select name="img_type">" >
            <option <?php echo $raw_selected;?>   >raw
            <option <?php echo $chip_selected;?>  >chip
            <option <?php echo $warp_selected ;?> >warp
            <option <?php echo $stack_selected;?> >stack   
            <option <?php echo $diff_selected;?>  >diff
        </select>
    </td>
</table>
</td>

<td>
&nbsp;<b>ID:</b>&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="text" name="id" value= <?php echo $rvar_id; ?> >
&nbsp;&nbsp;&nbsp;&nbsp;
<b>
<?php if ($rvar_project == "gpc1") {
        echo "Chip ID:";
      } else {
        echo "Class ID:";
      }
?>
</b>
&nbsp;<input type="text" name="class_id" size=10 value="<?php echo $rvar_class_id;?>" >

&nbsp;&nbsp;&nbsp;&nbsp;
<!-- add text input field for Cell ID, not used yet -->

<!--
<b>Cell ID:</b>&nbsp;<input type="text" name="cell_id" size=10 value="<?php echo $rvar_cell_id;?>" >

-->

</td>

</tr>

<!-- third row of table just contains a blank column followed by the user tag input -->
<tr>
<!-- blank label -->
<td width=20% > </td>
<!-- user tag input text -->
<td>&nbsp;<b>Stamp Name:</b>&nbsp;<input type="text" name="user_tag" size=60 value=<?php echo $rvar_user_tag; ?> ></td>
</tr>

</table> <!-- end of Image selector table -->

<!-- a blank row for space-->
<tr height=20><td></td></tr>

<!-- next row of main table contains the ROI input UI -->
<tr align=center width=100%>
    <td>
    <!-- 2 row by 6 column table -->
    <table width=100%>
    <thead>
    <tr>
    <!-- <td></td><td></td><td><b>Center</b></td><td></td><td></td><td><b>Range</b></td> -->
    <td><td><td><b>Center</b><td><td><td><b>Range</b>
    </tr>
    </thead>
    <tr>
        <td>
            <input type=radio name="center_type" value="Sky" <?php echo $sky_checked; ?> >Sky
        </td>
        <td>
            &nbsp;
            RA:
            &nbsp;
            &nbsp;
            <input type="text" name="RA" size=15  value= <?php echo $rvar_RA; ?> >
        </td>
        <td>
            &nbsp;
            DEC:
            &nbsp;
            <input type="text" name="DEC" size=15 value="<?php echo $rvar_DEC;?>" >
        </td>
        <td>
            <input type=radio name="range_type" value="Sky" <?php echo $rsky_checked; ?> >Sky
        </td>
        <td>
            &nbsp;
            dRA:
            &nbsp;
            &nbsp;
            &nbsp;
            <input type="text" name="dRA" size=15  value= <?php echo $rvar_dRA; ?> >
        </td>
        <td>
            &nbsp;
            dDEC:
            &nbsp;
            <input type="text" name="dDEC" size=15 value="<?php echo $rvar_dDEC;?>" >
        </td>
    </tr>
    <tr>
        <td>
            <input type=radio name="center_type" value="Pixels" <?php echo $pix_checked; ?> >Pixels
        </td>
        <td>
            &nbsp;
            X:
            &nbsp;
            &nbsp;
            &nbsp;
            <input type="text" name="X" size=15  value= <?php echo $rvar_X; ?> >
        </td>
        <td>
            &nbsp;
            Y:
            &nbsp;
            &nbsp;
            &nbsp;
            <input type="text" name="Y" size=15 value="<?php echo $rvar_Y;?>" >
        </td>
        <td>
            <input type=radio name="range_type" value="Pixels" <?php echo $rpix_checked; ?> >Pixels
        </td>
        <td>
            &nbsp;
            width:
            &nbsp;
            &nbsp;
            <input type="text" name="W" size=15  value= <?php echo $rvar_W; ?> >
        </td>
        <td>
            &nbsp;
            height:
            &nbsp;
            <input type="text" name="H" size=15 value="<?php echo $rvar_H;?>" >
        </td>
    </tr>
    </table>
    </td>
</tr>


<!-- next row of the main table just contains the Submit button -->

<tr align=center width=100% height=50>
  <td>
  <table width=40%>
  <tr>

<?php
  if ($request_id == 0): ?>
    <td><input type=submit value="Submit"></td>
    <td><b>Mode:</b>&nbsp;&nbsp;
    <input type=radio name="cmd_mode" value="Make Stamps"<?php echo $pstamp_checked; ?> >Make Stamps
    <input type=radio name="cmd_mode" value="Get Images" <?php echo $get_checked; ?> >Get Images
    <input type=radio name="cmd_mode" value="List Images" <?php echo $list_checked; ?> >List Images
    </td>
<?php 
  else: ?>
    <td><input type=submit value="Get Status"></td>
<?php
  echo "<td><b>Request Id: $request_id";
  endif; ?>

  </tr>
  </table>
  </td>
</tr>

<!--- next row in the main table is the Results of the previous request --->

<tr>
    <td>
    <b>Command:</b>&nbsp;&nbsp; <?php echo "$command_line\n";?>
    </td>
</tr>
<tr>
    <td>
    <b>Status:</b>&nbsp;&nbsp;&nbsp; <?php echo "$command_status\n";?>
    </td>
</tr>
<tr>
    <td>
    <b>Error:</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
        <?php 
            if ($error_line) {
                echo "<pre>";
                echo "$error_line\n";
                echo "<pre>\n";
            }
        ?>
    </td>
</tr>

<!-- a blank row for space -->
<tr height=20><td> </td></tr>

<tr>
<td>
<table align=center width=100% rules=none>
<caption height=10 valign=center><b>Results</b></caption>


<?php 
    $size = sizeof($output_array);
    if ($command_status == 0) {
        if ($list_checked) {
            // in list mode the output is a list of image files, just list them
            // later we might add links to cause a stamp to be made from a selected file
            for ($i = 0; $i < $size; $i++)  {
                echo "<tr><td>$output_array[$i]</td></tr>";
            }
        } else {
            // output the list of urls
            for ($i = 0; $i < $size; $i++)  {
                printURL($output_array[$i]);
            }
        }
    }
?>
</table>
</td>
</tr>
<!-- a blank row for our hidden element here-->

<!-- request_id being non-zero causes us to issue status requests instead of new requsts -->
<!--

need a way to cancel a request There's probably no reason to have the value hidden, but we do
need to set it as the last thing that we do

-->

<tr height=20>
<td>
    <input type="hidden" name="request_id" value=<?php echo $request_id ?> >
</td>
<td>
    <input type="hidden" name="last_request_id" value=<?php echo $last_request_id ?> >
</td>
<td>
    <input type="hidden" name="last_cmd_mode" value=<?php echo "\"$rvar_cmd_mode\"" ?> >
</td>
</tr>
</table>

<!-- The end -->

<p>
<pre>

<!--- rvar_select_by = <?php echo $rvar_select_by; ?>
--->

<?php 
    // dump parameters 

    // phpinfo(32);

?>

</body>
</form>

</html>
