#!/usr/bin/perl -w
#
# A script to browse the blind analysis database.
# 
# A.Gaponenko, May 2003

use Pg;

use CGI qw/:standard :html3/;
use CGI::Pretty qw( :html3 );

use File::Basename;
use lib dirname($0);
use RundbWebUtils;

sub decode_der {
    my $mask = shift;
    my @derlist = ("base", "rho", "eta", "xi", "delta", "xixidelta", "xidelta");
    my @ans;
    for(my $i=0; $i<=$#derlist; $i++) {
	my $match = 3 & ($mask >> (2*$i));
	next unless $match;
	if($match == 3) {
	    push @ans, $derlist[$i];
	}
	elsif( $match == 1 ) {
	    push @ans, $derlist[$i] . "+";
	}
	else {
	    push @ans, $derlist[$i] . "-";
	}
    }
    return @ans;
}

sub decode_rc {
    my $rcc = shift;
    my @funclist = ("Born0", "Born,&nbsp;with&nbsp;exact&nbsp;electron&nbsp;mass", 
		    "O(alpha^1L^1)", "O(alpha)", 
		    "O(alpha,&nbsp;with&nbsp;exact&nbsp;electron&nbsp;mass)",
		    "O(alpha^2L^2)", "O(alpha^2L^1)", "O(alpha^3L^3)",
		    "NS0", "S0", "NS1", "S1", "INT", "F3NS", "F3SS", 
		    "Soft_pairs",
		    "Virtual_pairs", "Ad-hoc&nbsp;exponentiation",
		    );

    my @ans;
    for(my $i=0; $i<=$#funclist; $i++) {
#	if( 1 & ($rcc>>$i) ) {
	    push @ans, $funclist[$i];
#	}
    }
    return @ans;
}

#================================================================
my ($sql, $res);

my $dbname = "micheld05";
my $conninfo = "dbname=$dbname user=dbreader password=123";
my $conn= Pg::connectdb($conninfo);

die ("Can't connect to database \"$dbname\": " 
     . $conn->errorMessage . "\n" ) 
    if($conn->status != PGRES_CONNECTION_OK);

#----------------------------------------------------------------
$sql = "SELECT * from parset_defaults;";
$res = $conn->exec($sql);
die "Error doing \"$sql\" : " . $conn->errorMessage . "\n" 
    unless($res->resultStatus == PGRES_TUPLES_OK);

my $parsetdefaultstable = formatHtmlTable($res, 
					  {
					   'tableattr' => {
							   -frame => 'border',
							   -rules => 'all',
							   -border => '1',
							   -cellpadding => '5%' },
					   'cols' => {
						      'key_id' => {
								   'tdattr' => {-class=>'aligncenter'},
								  },
						     },
					  }
					  );

#----------------------------------------------------------------
$sql = <<EOF
    SELECT key_id,comment,
    to_char(imported, 'Mon DD YYYY, HH24:MI:SS TZ ') as date 
    FROM cryptokeys
    ORDER BY key_id
    ;
EOF
    ;

$res = $conn->exec($sql);
die "Error doing \"$sql\" : " . $conn->errorMessage . "\n" 
    unless($res->resultStatus == PGRES_TUPLES_OK);

my $keytable = formatHtmlTable($res, 
			       {
				'tableattr' => {
						-frame => 'border',
						-rules => 'all',
						-border => '1',
						-cellpadding => '5%' },

				'cols' => {
					   'key_id' => {
							'tdattr' => {-class=>'aligncenter'},
						       },
					   'date' => {
						      'head' => 'import date',
						     },
					   'comment' => {
							 'tdattr' => {-class=>'alignleft'},
							},
					  },
			       } 
			       );

#----------------------------------------------------------------
$sql = <<EOF
    SELECT parset,key_id,tolerances,
    sum(madesamples*samplesize) as usedevents,
    parameters,
    to_char(created, 'Mon DD YYYY, HH24:MI:SS TZ ') as created,
    case when closed IS NULL then 'available' 
    else 'forgotten on ' || to_char(closed, 'Mon DD YYYY, HH24:MI:SS TZ ')
    end AS availability
    FROM parsets
    NATURAL LEFT OUTER JOIN michelpar_cleartext
    NATURAL LEFT OUTER JOIN spectra
    GROUP BY parset,key_id,tolerances,parameters,created,availability
    ORDER BY parset
    ;
EOF
    ;

$res = $conn->exec($sql);
die "Error doing \"$sql\" : " . $conn->errorMessage . "\n" 
    unless($res->resultStatus == PGRES_TUPLES_OK);

my $settable = formatHtmlTable($res, 
			       {
				'tableattr' => {
						-frame => 'border',
						-rules => 'all',
						-border => '1',
						-cellpadding => '5%',
					       },
			
				'cols' => {
					   'parset' => {
							'tdattr' => {-class=>'aligncenter'},
						       },
					   'key_id' => {
							'tdattr' => {-class=>'aligncenter'},
						       },
					   'parameters' => {
							    'head' => 'decryption result',
							    'tdattr' => {-class=>'alignleft'},
							   },
					   'created' => {
							 'tdattr' => {-class=>'alignleft'},
							},
					   'availability' => {
							      'tdattr' => {-class=>'alignleft'},
							     },
					  }
			       }
			       );
#----------------------------------------------------------------
$sql = <<EOF
    SELECT spectrum,parset,upper_bound,rcc,aldp_frac,mask,samplesize,reqsamples,madesamples,
    to_char(enddate, 'Mon DD YYYY, HH24:MI:SS TZ ') as finished
    FROM spectra
    ORDER BY spectrum
    ;
EOF
    ;

$res = $conn->exec($sql);
die "Error doing \"$sql\" : " . $conn->errorMessage . "\n" 
    unless($res->resultStatus == PGRES_TUPLES_OK);

my $spectrumtable 
    = formatHtmlTable($res, 
		      {
		       'tableattr' => {
				       -frame => 'border',
				       -rules => 'all',
				       -border => '1',
				       -cellpadding => '5%' },

		       'cols' => {
				  'upper_bound' => {
						    'head' => 'Upper<br>bound',
						    'content' => sub {
						      my $upper_bound= shift;
						      #return join('&nbsp;+<br>', decode_rc($rcc));
						      return $upper_bound;
						    }
						   },
				  'rcc' => {
					    'head' => 'RC number',
					    'content' => sub {
					      my $rcc = shift;
					      #return join('&nbsp;+<br>', decode_rc($rcc));
					      return $rcc;
					    }
					   },
				  'aldp_frac' => {
						  'head' => 'soft pair<br>energy fraction',
						 },
				  
				  'mask' => {
					     'head' => 'spectrum type',
					     #'tdattr' => {-class=>'aligncenter'},
					     'content' => sub {
					       my $mask = shift;
					       return join(':', decode_der($mask));
					     }
					    },
				  'reqsamples' => {
						   'head' => undef,
						  },
				  'samplesize' => {
						   'head' => 'sample<br>size',
						  },
				  'madesamples' => {
						    'head' => 'samples<br>produced',
						   },
				  #			      'finished' => {
				  #				  'tdattr' => {-class=>'alignright'},
				  #			      },

				 }
		      }
		      );
#----------------------------------------------------------------
# Mina 
$sql = 'SELECT distinct rcc,rcc as rctext FROM spectra;';
$res = $conn->exec($sql);
die "Error doing \"$sql\" : " . $conn->errorMessage . "\n" 
    unless($res->resultStatus == PGRES_TUPLES_OK);

my $rctable  
    = formatHtmlTable($res, 
		      {
		       'tableattr' => {
				       -frame => 'border',
				       -rules => 'all',
				       -border => '1',
				       -cellpadding => '5%' },

		       'cols' => {
				  'rc' => {
					   'head' => 'RC number',
					  },
				  'rctext' => {
					       'head' => 'radiative corrections -- not correct -- waiting for input from Andrei',
					       'tdattr' => {-class=>'alignleft'},
					       'content' => sub {
						 my $rcc = shift;
						 return join('&nbsp;+ ', decode_rc($rcc));
					       }
					      },
				 }
		      } 
		      );

#================================================================

my $q = new CGI;

my $title = "TWIST blind analysis database";

print
    $q->header(-expires=>'+5s', -charset=>'utf-8'),
    $q->start_html(-title=>$title,
		   -meta=>{'AUTHOR'=>'Andrei Gaponenko and Mina Nozar'},
		   -style=>{-src=>'styles.css'}),
    $q->h1($title),

    $q->div($q->h2("Imported public keys"), 
	    $q->p($keytable)),

    $q->div($q->h2("Parset defaults"),
	    $q->p("These public key and parameters would be used to create a new parset if it were requested now."),
	    $q->p($parsetdefaultstable)),

    $q->div($q->h2("Sets of Michel parameters"), 
	    $q->p("Tolerances are on (rho, eta, xi, delta), in this order."),
	    $q->p($settable)),

    #$q->div($q->h2("Generated spectra"), 
    $q->div($q->h2("Spectra available on disk"), 

	    $q->p("See below for an explanation of RC numbers."),

	    $q->p($spectrumtable)),
    
    $q->div($q->h2("Radiative correction versions"),
	    $q->p($rctable)
	    ),

    $q->end_html
    ;

exit 0;
#EOF
