#!/usr/bin/perl
use warnings;
use strict;
use JSON;

my $buffer;
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "GET") {
    $buffer = $ENV{'QUERY_STRING'};
    my $params_ref = &parse_query($buffer);

    print "$ENV{SERVER_PROTOCOL} 200 OK\r\n";
    print "Content-type:text/plain\r\n";
    print "\r\n";
    print "Hello\n";
    
    for my $key (keys %$params_ref) {
        print "$key => $params_ref->{$key}\r\n";
    }

} elsif ($ENV{'REQUEST_METHOD'} eq "POST") {
    read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
    my $obj_ref = &parse_json_body($buffer);

    print "$ENV{SERVER_PROTOCOL} 200 OK\r\n";
    print "Server: $ENV{SERVER_SOFTWARE}\r\n";
    print "Content-type:application/json\r\n";
    print "\r\n";
    print &encode_json($obj_ref)."\r\n";
    print $obj_ref->{'name'};
    
}

sub parse_json_body {
    return &decode_json($_[0]);
}

sub parse_query {
    my %params;
    my @pairs = split(/&/, $_[0]);
    foreach my $pair (@pairs) {
        my ($name, $value) = split(/=/, $pair);
        $value =~ tr/+/ /;
        $value =~ s/%(..)/pack("C", hex($1))/eg;
        $params{$name} = $value;
    }
    return \%params;
}

__END__

