#! /usr/local/bin/perl -w

use warnings;
use strict;

use IPC::Cmd 0.36 qw( can_run run);
use PS::IPP::Metadata::List qw( parse_md_list );
use PS::IPP::Config 1.01 qw( :standard );
use DateTime;

my $pi = 4 * atan2(1,1);

sub asin { atan2($_[0], sqrt(1 - $_[0] * $_[0])) }


my $ipprc =  PS::IPP::Config->new(); # IPP Configuration
my $siteConfig = $ipprc->{_siteConfig};

my $dbname;
unless(defined($dbname)) {
    $dbname = 'gpc1';
}
my $db = init_gpc_db();

my $neblocate = '/home/panstarrs/ipp/psconfig//ipp-20120802.lin64/bin/neb-locate';
my $fields    = '/home/panstarrs/ipp/psconfig//ipp-20120802.lin64/bin/fields';

my $db_query;
my $arg;
my $max_arg;
my $dt = DateTime->now(time_zone => 'Pacific/Honolulu');
$max_arg = $dt->ymd;
$dt->subtract( days => 1);
$arg = $dt->ymd;
open(OUT, ">/home/panstarrs/ippm/pointing_data/pointing.${arg}");
$db_query = "select exp_name,dateobs,alt,az,airmass,filter,ra * 180 / PI(),decl * 180 / PI(),CONCAT(path_base,'.smf'),camProcessedExp.quality,camProcessedExp.fault from camRun JOIN camProcessedExp USING(cam_id) JOIN chipRun USING(chip_id) JOIN rawExp USING(exp_id) where dateobs > '$arg' AND dateobs <= '$max_arg' AND camRun.label LIKE '%nightly%' ORDER BY dateobs";
    
print OUT "## $db_query\n";
my $data_ref = $db->selectall_arrayref( $db_query );

print OUT "#exp_name dateobs_D dateobs_T filter RA DEC ROT ALT AZ SHUTOPEN SHUTCLOS SHUTCUTC SHUTOUTC AST_R0 AST_D0 AST_T0 AST_S0 AST_RS AST_DS RA_TRUE DEC_TRUE AZALTTIM\n";
foreach my $row_ref (@{ $data_ref }) {
    my ($exp_name,$dateobs,$alt,$az,$airmass,$filter,$ra,$dec,$smf,$quality,$fault) = @{ $row_ref };
    my $disk_file = `$neblocate --server http://ippc03/nebulous  --path $smf`;
    chomp($disk_file);

    open(H,"echo '$disk_file' | $fields AST_R0 AST_D0 AST_T0 AST_S0 AST_RS AST_DS POSANGLE ROT |");
    my ($file,$r0,$d0,$t0,$s0,$rs,$ds,$pos,$rot,$sop,$scl,$scut,$sout);
    my ($sop_D,$sop_T,$scl_D,$scl_T,$scut_D,$scut_T,$sout_D,$sout_T,$azalttim);
    while (<H>) {
	chomp;
	($file,$r0,$d0,$t0,$s0,$rs,$ds,$pos,$rot) = split /\s+/;
    }
    close(H);

    open(H,"echo '$disk_file' | $fields -x 1 SHUTOPEN SHUTCLOS SHUTCUTC SHUTOUTC AZALTTIM|");
    while (<H>) {
	chomp;
	($file,$sop_D,$sop_T,$scl_D,$scl_T,$scut_D,$scut_T,$sout,$azalttim) = split /\s+/;
	$sop = "${sop_D}T${sop_T}";
	$scl = "${scl_D}T${scl_T}";
	$scut = "${scut_D}U${scut_T}";
#	$sout = "$sout_D $sout_T";
    }
    close(H);

    my ($xsp,$ysp,$x,$y,$R,$sinF,$cosF,$rho,$sinQ,$cosQ,$sinD,$cosD,$dec_T,$ra_T,$sinA,$cosA);
    # Calculate pixel scale in radians
    my $ra_bore = $ra;
    my $dec_bore = $dec;
    $xsp = 7.08161543662353E-05 * $pi / 180.0;
    $ysp = 7.08794419479912E-05 * $pi / 180.0;
# Construct radian offsets values
    $x = $r0 * $xsp;
    $y = $d0 * $ysp;
# Calculate phi angle
    $R = sqrt($x * $x + $y * $y);
    if ($R == 0) {
        $sinF = 0;
        $cosF = 1;
    }
    else {
        $sinF = $x / $R;
        $cosF = -1.0 * $y / $R;
    }
# Calculate theta angle
    $rho = sqrt(1 + $R * $R);
    $sinQ = 1 / $rho;
    $cosQ = $R / $rho;
# Scale factor for declination
    $sinD = sin($dec_bore * $pi / 180.0);
    $cosD = cos($dec_bore * $pi / 180.0);
# Calculate final values
    $dec_T = asin($sinQ * $sinD - $cosQ * $cosF * $cosD) * (180.0 / $pi);
    $sinA = 1.0 * $cosQ * $sinF;
    $cosA = 1.0 * $cosQ * $cosF * $sinD + $sinQ * $cosD;
    $ra_T = atan2($sinA,$cosA) * (180.0 / $pi) + $ra_bore;

    print OUT"$exp_name $dateobs $filter $ra $dec $rot $alt $az $sop $scl $scut $sout $r0 $d0 $t0 $s0 $rs $ds $ra_T $dec_T $azalttim\n";
}

close(OUT);


sub init_gpc_db {
    ## change to use the siteConfig setting, while readonly probably do not want to use a readonly replicated DB incase it gets behind
    my $dbserver = metadataLookupStr($siteConfig, 'DBSERVER');
    my $dbuser = metadataLookupStr($ipprc->{_siteConfig}, "RO_DBUSER");
    my $dbpass = metadataLookupStr($ipprc->{_siteConfig}, "RO_DBPASSWORD");
    die "database configuration not set up" unless defined($dbserver);
    die "database configuration not set up" unless defined($dbuser);
    die "database configuration not set up" unless defined($dbpass);
    #my $dbserver = 'ippdb01';
    #my $dbuser = 'ippuser';
    #my $dbpass = 'ippuser';
    use constant DB_SOCKET => '/var/run/mysqld/mysqld.sock';
    $db = DBI->connect("DBI:mysql:database=${dbname};host=${dbserver};" .
                       "mysql_socket=" . DB_SOCKET(),
                       ${dbuser},${dbpass},
		       { RaiseError => 1, AutoCommit => 1}
        ) or die "Unable to connect to database $DBI::errstr\n";
    return($db);
}

