package xml_primer_order;

use strict;
use vars qw(@ISA @EXPORT);
use Exporter;
@ISA = ('Exporter');
@EXPORT = qw(&create_order);

sub create_order {
    my($SENDER_DATA,$PLATE_DATA,$DATA,$debug) = @_;

    my $xmlLocal = exists($ENV{XML_LOCAL_WRITE}); # TODO
    #print STDOUT "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"; # TODO
    #die "FORCED QUIT ! xmlLocal = $xmlLocal\n";   # TODO
    

    my %SENDER_DETAILS = %$SENDER_DATA;
    my %PRIMER_PLATE_DATA = %$PLATE_DATA;
    my %PRIMER_ORD_DATA = %$DATA;

    if (($SENDER_DETAILS{'Account'} eq '') || (!$SENDER_DETAILS{'Account'})){
        print "Account details are not supplied, please add and resubmit the order\n" if $debug ==1;
        my $statement = "Account details are not supplied, please add and resubmit the order";
        return $statement;
    }

    ##FOR THE FILE_TYPE entry to define the destination of 
    ##the xml output file. An omitted field means that the file will
    ##be written to the local home directory.
    my $DIR = {
        "SIGMA_HTTPS_TEST" => '/nfs/privateftp/ftp-primer/private/TEST_HTTPS/',
        "SIGMA_HTTPS_TEMP" => '/nfs/privateftp/ftp-primer/private/UNENCRYPTED/SANGER_FINISHING/',
        "SIGMA_HTTPS_LIVE" => '/nfs/privateftp/ftp-primer/private/HTTPSTAGING/',
    };
    my %BASE_DIR=%$DIR;    
    
    my @clist = localtime(time);
    if (length($clist[1])==1){
        $clist[1]='0'.$clist[1];
    }
    
    if (length($clist[0])==1){
        $clist[0]='0'.$clist[0];
    }
    $clist[5] = ($clist[5]+1900);
    $clist[4] = ($clist[4]+1);
    if (length($clist[3])==1){
        $clist[3]='0'.$clist[3];
    }
    if (length($clist[4])==1){
        $clist[4]='0'.$clist[4];
    }
    my $c_date = $clist[5].'-'.$clist[4].'-'.$clist[3].'T'.$clist[2].':'.$clist[1].':'.$clist[0];
    my $order_date = $clist[3].'/'.$clist[4].'/'.$clist[5];
    my $time = $clist[5].$clist[4].$clist[3].$clist[2].$clist[1].$clist[0];

    print "time list - @clist $c_date\n" if $debug ==1;
    print ">>TIME - $time<<\n" if $debug ==1;

    ##define hash keys that may not exist
    ##they may or may not be used dependent on the supplier
    $SENDER_DETAILS{'T_Date'}=$c_date unless $SENDER_DETAILS{'T_Date'};
    $SENDER_DETAILS{'Full_Date'}=$time unless $SENDER_DETAILS{'Full_Date'};
    $PRIMER_PLATE_DATA{'OrderDate'}=$order_date unless $PRIMER_PLATE_DATA{'OrderDate'};
 
    $PRIMER_PLATE_DATA{'Comment1'}='' if !$PRIMER_PLATE_DATA{'Comment1'};
    $PRIMER_PLATE_DATA{'Comment2'}='' if !$PRIMER_PLATE_DATA{'Comment2'};
    $PRIMER_PLATE_DATA{'Comment3'}='' if !$PRIMER_PLATE_DATA{'Comment3'};

    if ($debug==1){
        
        print "HASH OF HASH CONTENTS sender details----------->\n";
        print Data::Dumper::Dumper(\%SENDER_DETAILS);
        print "----------------------------------------->\n";
        
        print "HASH OF HASH CONTENTS primer plate details----------->\n";
        print Data::Dumper::Dumper(\%PRIMER_PLATE_DATA);
        print "----------------------------------------->\n";
        
        
        print "HASH OF HASH CONTENTS primer order details----------->\n";
        print Data::Dumper::Dumper(\%PRIMER_ORD_DATA);
        print "----------------------------------------->\n";
    
    }

    my $default_sender;
    
    my $SUPPLIER_TO = {
        "sigma" => 'sysadmin@europe.sial.com',
    };

    my %SUPPLIER = %$SUPPLIER_TO;

    my $payload = $SENDER_DETAILS{'Purchase_Order'}.'.'.$SENDER_DETAILS{'Full_Date'};
    my $full_date = $SENDER_DETAILS{'T_Date'};
    my $dtd_file = $SENDER_DETAILS{'Supplier'}.'_primer_order.dtd';

    my $file;

    if ($xmlLocal){
	$file = "./".$SENDER_DETAILS{'FileName'}.'.xml';   # TODO
    } else { # TODO
	$file = $BASE_DIR{$SENDER_DETAILS{'File_Type'}}.$SENDER_DETAILS{'FileName'}.'.xml'; # TODO
    } # TODO


    my $person = $SENDER_DETAILS{'Orderer'};
    $SENDER_DETAILS{'Sender'} = $SENDER_DETAILS{'Sender'}.'@sanger.ac.uk';
    $default_sender = $SENDER_DETAILS{'Default_Sender'} if $SENDER_DETAILS{'Default_Sender'} ne '';

    print "FILE = $file\n" if $debug==1;
    print "PAYLOAD = $payload\n" if $debug==1;

    if ($SENDER_DETAILS{'Supplier'} eq 'sigma') {
        
        if ((!$default_sender) || ($default_sender eq '')){
            $default_sender = 'ftp-primer@sanger.ac.uk';
        }

        #make a list of recipients.
        my $recipient_list;
        if ($SENDER_DETAILS{'Sender'} eq $default_sender) {
            $recipient_list =$SENDER_DETAILS{'Sender'};
        } else {
#            $recipient_list = (join',', $SENDER_DETAILS{'Sender'},$default_sender);
            $recipient_list =(join',', $SENDER_DETAILS{'Sender'},'kva@sanger.ac.uk');
        }

##main identification block
my $all = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE Sanger SYSTEM \"$dtd_file\">
<Sanger payloadID=\"$payload\@sanger.ac.uk\" xml:lang=\"en-US\" timestamp=\"$full_date\">
<Header>
<From>
<Credential domain=\"custom\">
<Identity>$recipient_list</Identity>
</Credential>
</From>
<To>
<Credential domain=\"custom\">
<Identity>$SUPPLIER{$SENDER_DETAILS{'Supplier'}}</Identity>
</Credential>
</To>
<Sender>
<Credential domain=\"custom\">
<Identity>$default_sender</Identity>
<SharedSecret>$SENDER_DETAILS{'Secret_Passphrase'}</SharedSecret>
</Credential>
</Sender>
</Header>
<Request>
<OrderRequest ID=\"$SENDER_DETAILS{'PO_Prefix'}$SENDER_DETAILS{'Purchase_Order'}\">
<OligoOrder ID=\"Root\">
<OligoHeader>
<AccountNumber>$SENDER_DETAILS{'Account'}</AccountNumber>
<PONumber>$SENDER_DETAILS{'PO_Prefix'}$SENDER_DETAILS{'Purchase_Order'}</PONumber>
<Priority>$SENDER_DETAILS{'Priority'}</Priority>";

##plate identification block
$all.="
<StockPlateNumber>$PRIMER_PLATE_DATA{'StockPlateNumber'}</StockPlateNumber>
<StockPlateID>$PRIMER_PLATE_DATA{'StockPlateID'}</StockPlateID>
<WorkingPlateNumber set=\"1\">$PRIMER_PLATE_DATA{'WorkingPlateNumber'}</WorkingPlateNumber>
<WorkingPlateID set=\"1\">$PRIMER_PLATE_DATA{'WorkingPlateID'}</WorkingPlateID>
<OrderDate>$PRIMER_PLATE_DATA{'OrderDate'}</OrderDate>
<PersonName>$person</PersonName>
<Comment1 ID=\"Team\">$PRIMER_PLATE_DATA{'Comment1'}</Comment1>
<Comment2 ID=\"MPID\">$PRIMER_PLATE_DATA{'Comment2'}</Comment2>
<Comment3 ID=\"LPID\">$PRIMER_PLATE_DATA{'Comment3'}</Comment3>
<OligoCount>$PRIMER_PLATE_DATA{'OligoCount'}</OligoCount>
</OligoHeader>
<OligoDetail ID=\"$SENDER_DETAILS{'PO_Prefix'}$SENDER_DETAILS{'Purchase_Order'}\">";

##iterative block
        my $primer_count =0;
        foreach my $keys (sort {sensibly($PRIMER_ORD_DATA{$a}{'OligoName'}, $PRIMER_ORD_DATA{$b}{'OligoName'})} keys %PRIMER_ORD_DATA){
            $primer_count++;
            $all.="
<OligoLine ID=\"$primer_count\">
<OligoName>$PRIMER_ORD_DATA{$keys}{'OligoName'}</OligoName>
<OligoSequence>$PRIMER_ORD_DATA{$keys}{'OligoSequence'}</OligoSequence>
<OligoScale>$PRIMER_ORD_DATA{$keys}{'OligoScale'}</OligoScale>
<OligoPurification>$PRIMER_ORD_DATA{$keys}{'OligoPurification'}</OligoPurification>
<OligoNotes>$PRIMER_ORD_DATA{$keys}{'OligoNotes'}</OligoNotes>
<OligoWells>$PRIMER_ORD_DATA{$keys}{'OligoWells'}</OligoWells>
</OligoLine>";
        }
        
##end block
        $all.="
</OligoDetail>
</OligoOrder>
</OrderRequest>
</Request>
</Sanger>";
        
        print "$all\n" if $debug==1;
        open (SOURCE, "> $file");
        print SOURCE "$all";
        close (SOURCE);
        my $code = system("chmod 0664 $file");
        print "\nORDER FILE created at $file.\n" if $debug ==1;
        return $code;
    }
    
    
}

sub sensibly {
    my ($aa, $bb) = @_;
    my ($a_lhs, $b_lhs);
    
    return $aa cmp $bb if $aa eq "" or $bb eq "";
    $aa =~ s/^(\D+|\d+)//;
    $a_lhs = lc($1);
    
    $bb =~ s/^(\D+|\d+)//;
    $b_lhs = lc($1);
    
    if ($a_lhs =~ /^[0-9]/ and $b_lhs =~ /^[0-9]/) {
        if ($a_lhs == $b_lhs) {
            return sensibly($aa, $bb);
        } else {
            return $a_lhs <=> $b_lhs;
        }
    } else {
        if ($a_lhs eq $b_lhs) {
            return sensibly($aa, $bb);
        } else {
            return $a_lhs cmp $b_lhs;
        }
    }
}


1;
