#!/usr/bin/perl

use strict;

use Mysql;
use XML::DOM;
use POSIX ":sys_wait_h";
use Time::HiRes;
use Compress::Zlib;

print "Content-type: text/plain\n\n";

#----------------------------------------
# Parse incoming data
#----------------------------------------
my $buffer;
my %params;
my $cmd = "";

if($ENV{REQUEST_METHOD} eq 'POST')
{
    read(STDIN, $buffer, $ENV{CONTENT_LENGTH});
    $buffer = Compress::Zlib::memGunzip($buffer) if ($ENV{HTTP_X_SATIS_ENCODING} || '') =~ /gzip/; 
    $buffer .= "&";
    $buffer .= $ENV{QUERY_STRING};
} 
else
{
    $buffer = $ENV{QUERY_STRING};
}
my @pairs = split(/&/, $buffer);
my $pair;

foreach $pair(@pairs)
{
    (my $key, my $value) = split(/=/, $pair);
    $value =~ tr/+/ /;
    $value =~ s/%0D%0A/"%0A"/eg;
    $value =~ s/%([A-Fa-f0-9]{2})/pack("C",hex($1))/eg;
    
    if (defined $params{$key})
    {
        $params{$key} .= "\t$value";
    } 
    else
    {
        $params{$key} = $value;
    }
}

#--- Gereral Parameters Definition
my $opt_user="satis";
my $opt_password="satis";
my $opt_base="satis";
my $socket="/tmp/mysql.sock"; 
# Определяем используемый сокет
$ENV{"3306"}="$socket";

my $conf="/usr/local/controller/scripts/scripts.conf";
open(CONF,$conf) or die "Can't open config file!";
my $confparam="";
my $confvalue;

while(<CONF>){
    chomp();
#    print $_ . "\n";
    ($confparam,$confvalue)=split(/=/);
    if(defined($confvalue)){
        if($confparam eq "dbuser") {
	    $opt_user=$confvalue;
	}
        elsif($confparam eq "dbpass") {
	    $opt_password=$confvalue;
	}
        elsif($confparam eq "db") {
	    $opt_base=$confvalue;
	}
	else {}
    }
    else {
#	print "WARNING: split didn't find '=' in line.\n";
    }
}
close(CONF);

#--- Mysql connection 
my $dbh = Mysql->connect("", "$opt_base", "$opt_user", "$opt_password") ||
        die "Can't connect\n";
#--- End of section

#
#<spectra>
# <spectrum id="..." />
# <spectrum id="..." />
# <spectrum id="..." />
#</spectra>
#
#<spectra>
# <spectrum id="...">
#  <point freq="..."><![CDATA[...]]></point>
#  <point freq="..."><![CDATA[...]]></point>
#  <point freq="..."><![CDATA[...]]></point>
# </spectrum>
#</spectra>

my $strtoparse = $params{"xml"};
#open(FILE, "> ARMgetSpectrum.IN.txt");
#print FILE $strtoparse;
#close(FILE);
my $parser = new XML::DOM::Parser;
my $indoc = $parser->parse($strtoparse);

my $currenttime = sprintf("%.f", Time::HiRes::time*1000);

my $outdoc = new XML::DOM::Document;
my $out_spectra = $outdoc->createElement("spectra");
$outdoc->appendChild($out_spectra);

my $spectra = $indoc->getElementsByTagName("spectra")->item(0)->getElementsByTagName("spectrum");

my $i;
for ( $i = 0; $i < $spectra->getLength(); $i++ )
{
  my $spectrum = $spectra->item($i);
  my $id = $spectrum->getAttribute("id") or "";

  my $out_spectrum = $outdoc->createElement("spectrum");
  $out_spectra->appendChild($out_spectrum);
  $out_spectrum->setAttribute("id", $id);

  my $query;
  $query = "SELECT freq, sign FROM lastspectrum WHERE bandid=$id ORDER BY freq";
  my $sth = Query $dbh $query or die "$Mysql::db_errstr";

  my $line;
  while ( $line = $sth->fetchrow_arrayref )
  {
    my $freq  = $$line[0];
    my $value = $$line[1];

    my $point = $outdoc->createElement("point");
    $out_spectrum->appendChild($point);
    $point->setAttribute("freq", $freq);
    if ( $value ne "" )
    {
      my $cdata=$outdoc->createCDATASection("cdata");
      $cdata->setData("$value");
      $point->appendChild($cdata);
    }
  }
  undef $sth;
}

#$outdoc->printToFile("ARMOutput.xml");
my $final = $outdoc->toString();
#$final =~  s/([^\w()'*~!.-])/sprintf '%%%02X', ord $1/eg;

print $final;

$outdoc->dispose;
$indoc->dispose;

undef $dbh;
