#!/usr/bin/perl
#use strict;
#use warnings;
use LWP::UserAgent;
use JSON qw( decode_json );
my $BCcode = "";
my $SNPcode = "";
my $searchterm = "";



my $ua = LWP::UserAgent->new;
my $server_endpoint = "http://www.cerealsdb.uk.net/cerealgenomics/cgi-bin/parse_json_v3.cgi";
# set custom HTTP request header fields
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('content-type' => 'application/json');

### ASSIGN VARIABLES TO JSON QUERY HERE! ###
my $BCcode = "BC000000118";
#my $SNPcode = "BS00003644";
#my $searchterm = "rht";

# add POST data to HTTP request body
my $string1 = '{"services":[{"service":"FoobarKeywordContigservice","run":true,"parameter_set":{"parameters":[{"param":"contig_name","current_value":"';
my $string2 = '","tag":2,"type":"string","wheatis_type":11,"level":7,"concise":true},{"param":"SNP_id","current_value":"';
my $string3 = '","tag":1,"type":"string","wheatis_type":11,"level":7,"concise":true}]}},{"run":true,"services":"Searchservice","parameter_set":{"parameters":[{"param":"Search_term","current_value":"';
my $string4 = '","tag":3}]}}]}';


my $post_data = join ("", $string1 , $BCcode , $string2 , $SNPcode , $string3 , $searchterm , $string4);

#print $post_data."\n";

$req->content($post_data);
my $resp = $ua->request($req);


if ($resp->is_success) {
    my $message = $resp->decoded_content();

#### Prints out a the JSON message from CerealsDB when it receives the $post_data variable #####  
#    print "Received reply: $message\n";

}

#### Print error message if no connection is made ####
else {
    print "HTTP POST error code: ", $resp->code, "\n";
    print "HTTP POST error message: ", $resp->message, "\n";
}


my $decoded = decode_json($resp->decoded_content());
 

# This is a Perl example of parsing a JSON object.
 ### Print out BC information

# This is a Perl example of parsing a JSON array.
my @result = @{ $decoded->{'results'} };

foreach my $f ( @result ) {
  print "BC contig = ".$f->{"title"} . "\n";

	print "This is a ".$f->{"data"}{"format"} . "\n";

	my @data = @{  $f->{"data"}{"contains"} };
	foreach my $g (@data ) {
	print "The sequence is \n".$g->{"data"}. "\n";
	}

	my @putative = @{  $f->{"data"}{"putative"} };
        foreach my $h (@putative ) {
        print "\t contains the SNP ".$h->{"id"}. "\t";
	print " at position ".$h->{"position"}. "\n";
        }


	}

