<?php
include 'ipp.php';
include 'site.php';

$ID = checkID ();

// require an explicit project
if (! $ID['proj']) { projectform ($ID); }

$db = dbconnect($ID['proj']);

if ($ID['menu']) {$myMenu = $ID['menu'];}
else {$myMenu = "ipp.czartool.dat";}

menu($myMenu, 'Czartool', 'ipp.css', $ID['link'], $ID['proj']);

$pass = $ID['pass'];
$proj = $ID['proj'];
$menu = $ID['menu'];

$userSelection = $_GET[selection];

if ($userSelection == "") {$userSelection = $_POST['state'];}
if ($userSelection == "") {$userSelection = "new";}

$debug = 0;

$PATH = getenv("PATH");
putenv("PATH=$BINDIR:$PATH");

$LD_LIBRARY_PATH = getenv("LD_LIBRARY_PATH");
putenv("LD_LIBRARY_PATH=$LIBDIR:$LD_LIBRARY_PATH");

exec("czartool_getLabels.pl -s stdscience", $stdsLabels, $status);
exec("czartool_getLabels.pl -s distribution", $distLabels, $status);

if ($debug) {
    echo "prog returned $status, and output:<br>";
    for ($i = 0; $i < count($distLabels); $i++) {
        echo "$distLabels[$i]<br>";
    }
}

$states=array("full","new","drop","wait");
$stages=array("chip","cam","fake","warp","stack","diff","magic","destreak","dist");

// set up the form
echo "<form action=\"czartool_labels.php\" method=\"POST\">\n";

echo "<input type=\"hidden\" name=\"pass\" value=\"$pass\">\n";
echo "<input type=\"hidden\" name=\"proj\" value=\"$proj\">\n";
echo "<input type=\"hidden\" name=\"menu\" value=\"$menu\">\n";
echo "</form>\n";
$stateChosen = 0;
foreach ($states as &$state) {

    if ($userSelection == $state) {
        showAllLabels($pass, $proj, $db, $stdsLabels, $distLabels, $stages, $states, $state);
        $stateChosen=1;
        break;
    }
}

if (!$stateChosen) showOneLabel($pass, $proj, $db, $userSelection, $stages, $states);

menu_end();


###########################################################################
#
# Checks one label and prints results in a table
#
###########################################################################
function showOneLabel($pass, $proj, $db, $label, $stages, $states) {

    echo "<p> Current status for label '$label' (any faults are shown in parentheses) </p>";

    // set up table columns
    $class = "list";
    echo "<table class=$class>\n";
    echo "<tr><td></td>\n";
    write_header_cell($class, "state");
    foreach ($stages as &$stage) {write_header_cell($class, $stage);}
    echo "</tr>\n";

    // write rows
    foreach ($states as &$state) {

        $link = "czartool_labels.php?pass=" . $pass . "&proj=" . $proj . "&selection=" . $state;
        $defaultlink = "czartool_labels.php?pass=" . $pass . "&proj=" . $proj;

        echo "<tr><td></td>\n";
        write_table_cell($class, '%s', $link, $state);

        $str = "";
        $anyFaults = false; 
        $link = "chipProcessedImfile_failure.php?pass=" . $pass . "&proj=" . $proj . "&chipRun.label=" . $label . "&chipRun.state=new";
        getStateAndFaults($db, $label,"chipRun", $state, "chip", $str, $anyFaults);
        write_table_cell($class, '%s', $anyFaults ? $link : "", $str);

        $link = "camProcessedExp_failure.php?pass=" . $pass . "&proj=" . $proj . "&camRun.label=" . $label . "&camRun.state=new";
        getStateAndFaults($db, $label,"camRun", $state, "cam", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "", $str);

        $link = $defaultlink;
        getStateAndFaults($db, $label,"fakeRun", $state, "fake", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "", $str);

        $link = "warpFailedSkyfiles.php?pass=" . $pass . "&proj=" . $proj . "&warpRun.label=" . $label . "&warpRun.state=new";
        getStateAndFaults($db, $label,"warpRun", $state, "warp", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "",  $str);
        
        $link = "stackFailedSkyfile.php?pass=" . $pass . "&proj=" . $proj . "&stackRun.label=" . $label . "&stackRun.state=new";
        getStateAndFaults($db, $label,"stackRun", $state, "stack", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "", $str);

        $link = "diffFailedSkyfile.php?pass=" . $pass . "&proj=" . $proj . "&diffRun.label=" . $label . "&diffRun.state=new";
        getStateAndFaults($db, $label,"diffRun", $state, "diff", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "",  $str);

        $link = $defaultlink;
        getStateAndFaults($db, $label,"magicRun", $state, "magic", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "", $str);

        $link = $defaultlink;
        getStateAndFaults($db, $label,"magicDSRun", $state, "magicDS", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "", $str);
       
        $link = $defaultlink;
        getStateAndFaults($db, $label,"distRun", $state, "dist", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "", $str);

        echo "</tr>\n";
    }

    echo "</table>\n";

    echo "<p> - Click on a state to see all labels for that state <br>";
    echo "- Click on a fault to find logfile </p>";
}

###########################################################################
#
# Creates table for all labels showing all stages for given 'state'
#
###########################################################################
function showAllLabels($pass, $proj, $db, $stdsLabels, $distLabels, $stages, $states, $selectedState) {

    echo "<p> Current stdscience labels for '$selectedState' (any faults are shown in parentheses)</p>";

    // set up table columns
    $class = "list";
    //echo "<table class=$class BORDER=\"0\" CELLSPACING=\"0\" CELLPADDING=\"5\">\n";
    echo "<table class=$class >\n";
    echo "<tr><td></td>\n";
    write_header_cell($class, "label");
    write_header_cell($class, "distributing?");
    //    echo "<td class=\"$class\"><a href=\"$link\"> $myValue </a></td>\n";
    //    echo "<th class=\"$class\"><a href=\"czartool.php\">label</th>\n";

    foreach ($stages as &$stage) {write_header_cell($class, $stage);}
    //foreach ($stages as &$stage) {

    //  $link = "czartool.php?pass=" . $pass . "&proj=" . $proj . "&label=" . $stage;
    // echo "<th class=\"$class\"><a href=\"$link\">$stage</th>\n";
    // }

    echo "</tr>\n";

    // write rows
    foreach ($stdsLabels as &$stdsLabel) {

        $distributing = false;
        foreach ($distLabels as &$distLabel) {

            if ($stdsLabel == $distLabel) { $distributing = true; break;}
        }


        // create link to label summary page for each label
        $link = "czartool_labels.php?pass=" . $pass . "&proj=" . $proj . "&selection=" . $stdsLabel;
        $defaultlink = "czartool_labels.php?pass=" . $pass . "&proj=" . $proj;

        echo "<tr><td></td>\n";
        write_table_cell($class, '%s', $link, $stdsLabel);
        write_table_cell($class, '%s', "", $distributing ? "yes" : "NO");

        $str = "";
        $anyFaults = false; 

        $link = "chipProcessedImfile_failure.php?pass=" . $pass . "&proj=" . $proj . "&chipRun.label=" . $stdsLabel . "&chipRun.state=new";
        getStateAndFaults($db, $stdsLabel,"chipRun", $selectedState, "chip", $str, $anyFaults);
        write_table_cell($class, '%s', $anyFaults ? $link : "", $str);

        $link = "camProcessedExp_failure.php?pass=" . $pass . "&proj=" . $proj . "&camRun.label=" . $stdsLabel . "&camRun.state=new";
        getStateAndFaults($db, $stdsLabel,"camRun", $selectedState, "cam", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "", $str);

        $link = $defaultlink;
        getStateAndFaults($db, $stdsLabel,"fakeRun", $selectedState, "fake", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "", $str);

        $link = "warpFailedSkyfiles.php?pass=" . $pass . "&proj=" . $proj . "&warpRun.label=" . $stdsLabel . "&warpRun.state=new";
        getStateAndFaults($db, $stdsLabel,"warpRun", $selectedState, "warp", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "",  $str);
        
        $link = "stackFailedSkyfile.php?pass=" . $pass . "&proj=" . $proj . "&stackRun.label=" . $stdsLabel . "&stackRun.state=new";
        getStateAndFaults($db, $stdsLabel,"stackRun", $selectedState, "stack", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "", $str);

        $link = "diffFailedSkyfile.php?pass=" . $pass . "&proj=" . $proj . "&diffRun.label=" . $stdsLabel . "&diffRun.state=new";
        getStateAndFaults($db, $stdsLabel,"diffRun", $selectedState, "diff", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "",  $str);

        $link = $defaultlink;
        getStateAndFaults($db, $stdsLabel,"magicRun", $selectedState, "magic", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "", $str);

        $link = $defaultlink;
        getStateAndFaults($db, $stdsLabel,"magicDSRun", $selectedState, "magicDS", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "", $str);
       
        $link = $defaultlink;
        getStateAndFaults($db, $stdsLabel,"distRun", $selectedState, "dist", $str, $anyFaults);
        write_table_cell($class, '%s',  $anyFaults ? $link : "", $str);

        echo "</tr>\n";
    }

    echo "</table>\n";

    echo "<p> - Click on a label to see all states for that label (full, new, drop etc)<br>";
    echo "- Click on a fault to find logfile </p>";
}

###########################################################################
#
# Returns state and fault-count (if new) as a string
#
###########################################################################
function getStateAndFaults($db, $label, $table, $state, $stage, &$str, &$anyFaults) {

    $anyFaults = false;

    $str = checkLabel($db, $label, $table, $state, $stage);

    if ($state == "new") {

        $faults = countFaults($db, $label,$table,$stage);

        if ($faults > 0) {

            $str = $str."(".$faults.")";
            $anyFaults = true;
        }
    }
}

###########################################################################
#
# Returns count of exposures with this state for this label
#
###########################################################################
function checkLabel($db, $label, $table, $state, $stage) {

    $sql = "SELECT COUNT(state) FROM $table WHERE label LIKE '$label' AND state = '$state'";
    if ($debug) {echo "$sql<br>";}

    $qry = $db->query($sql);
    if (dberror($qry)) {echo "<b>error with $sql </b><br>\n";}
    if (!$qry->fetchInto($row)) {echo "<b>error with $sql </b><br>\n";}
    return $row[0];
}

###########################################################################
#
# Returns count of faults for this stage and label
#
###########################################################################
function countFaults($db, $label, $table, $stage) {

    $joinTable = 0;
    $id = $stage."_id";

    if ($stage == "chip") {$joinTable="chipProcessedImfile";}
    elseif ($stage == "cam") {$joinTable="camProcessedExp";}
    elseif ($stage == "fake") {$joinTable="fakeProcessedImfile";}
    elseif ($stage == "warp") {$joinTable="warpSkyfile";}
    elseif ($stage == "stack") {$joinTable="stackSumSkyfile";}
    elseif ($stage == "diff") {$joinTable="diffSkyfile";}
    elseif ($stage == "magic") {$joinTable="magicNodeResult";}
    elseif ($stage == "magicDS") {$id = "magic_ds_id"; $joinTable="magicDSFile";}
    elseif ($stage == "dist") {$joinTable="distComponent";}
    else {return -1;}

    $faultCol =  $joinTable.".fault";

    $sql = "SELECT COUNT(DISTINCT $id) FROM $table JOIN $joinTable USING ($id) WHERE label LIKE '$label' AND $faultCol != 0 AND $table.state = 'new'";
    if ($debug) {echo "$sql<br>";}

    $qry = $db->query($sql);
    if (dberror($qry)) {echo "<b>error with $sql </b><br>\n";}
    if (!$qry->fetchInto($row)) {echo "<b>error with $sql </b><br>\n";}
    return $row[0];
}
?>

