#!/usr/bin/perl
use JSON;
use Data::Dumper;

sub usage {
	print "USAGE: $0 [input_dir or file] [output_dir]\n";
	exit;
}

if (!defined($ARGV[0]) or !defined($ARGV[1])) {
	usage();
}

my $json = JSON->new->allow_nonref;
my $input_arg = $ARGV[0];
my @input;

my $out_dir = $ARGV[1];
$out_dir =~ s/\/$//g;

if (-d $input_arg ) {
    	opendir(DIR, $input_arg);
	for my $f (readdir(DIR)) {
		if ($f =~ /\.json$/) {
			print "file is $f\n";
			parse_file(join('/',$input_arg,$f));
		}
	}
}
else {
    if (-r $input_arg) {
        parse_file($input_arg);
    }
    else { usage() } 
}


sub parse_file {
	my ($filename) = @_;
	open(IN,$filename) or die "cant open input file\n";
        @input=<IN>;
        close(IN);

	my ($host,$port,$uri,$method);
	my @output;
	foreach(@input){
	    if (/Host:\s*(.*):?(\d+)?/i){
		$host = $1;
		$host =~ s/\s+//g;
		if  ( defined($2) ) { $port = $2; }
		else { $port = 80; }
	    }
	    
	    if (/^(GET|POST|PUT|OPTIONS)\s+(.*)\s+HTTP/) {
		$method = $1;
		$uri = $2;
	    }

	    last if ($_ !~ /\w+/); 
	    push (@output,$_);
	}
	$host =~ s/\./_/g;
	$uri =~ s/\//_/g;
	$uri =~ s/\./_dot_/g;
	$method = lc($method);
	my $output_filename = $out_dir . '/' . join('_',$host,$port,$uri);
	if ( -e $output_filename ) {
	    #print "already exists\n";
            #return;
	}
	open(OUT,">$output_filename") or die "cant open output file\n";

	my $last_line = scalar(@input) - 1;
	return if ($input[$last_line] !~ /\w+/ or $input[$last_line] !~ /{/);

	my $json_text = $input[$last_line];
	print "JSON: $json_text\n";
	my $perl_scalar = $json->decode( $json_text );

	## §
	foreach my $i ( keys %$perl_scalar) {
        #print "i: $i\n";
        #print "type is " . ref($$perl_scalar{$i}) . "\n"; 
	    print "filename is $filename\n";
	    print Dumper $$perl_scalar{$i};
	    ## TODO: fix this later... array is weird....
	    if (ref $$perl_scalar{$i} eq 'ARRAY') {
		return;
	    }
	    print "size: " . scalar(keys %{$$perl_scalar{$i}}) . "\n";
	    if (scalar(keys %{$$perl_scalar{$i}}) > 0) {
		foreach my $j ( sort keys %{$$perl_scalar{$i}} ) {
		    print "j: $j\n";
		    my $value = $$perl_scalar{$i}{$j};
		    $value = "§$value§";
		    $$perl_scalar{$i}{$j} = $value;
		}
	    }
	    else {
		my $value = $$perl_scalar{$i};
		$value = "§$value§";
		$$perl_scalar{$i} = $value;
	    }
	    
	}
	print $json->encode($perl_scalar);
	foreach(@output){
	    print OUT "$_";
	}
	print OUT "\n";
	print OUT $json->encode($perl_scalar);
}
