#!/usr/bin/perl -w
use strict;

use utf8;
use open ":utf8";
binmode STDOUT, ":utf8";

BEGIN {
    eval {
        require JSON;
        JSON->import();
    };
    eval {
        require JSON::XS;
        JSON::XS->import();
    } if $@;
    eval {
        require JSON::PP;
        JSON::PP->import();
    } if $@;
    die $@ if $@;
}

use FindBin;
use lib "$FindBin::Bin/lib";

use Utils::Common;

use Getopt::Long;
my %program_options;
GetOptions(\%program_options, 'all');

my $opt = $Utils::Common::options;
if ($program_options{all}) {
    print encode_json(filter_blessed($opt));
} else {
    my %h = map { $_ => traverse($opt, $_) } map { split /\s*,\s*/ } @ARGV;
    print encode_json(\%h);
}

sub traverse {
    my ($obj, $path) = @_;

    my @path = split /\./, $path;
    while (scalar @path) {
        return undef unless $obj;
        $obj = $obj->{shift @path};
    }
    return $obj;
}

sub filter_blessed {
    my $h = shift;
    if ( ref($h) && ref($h) !~ /HASH|ARRAY/ ) {
        return undef;
    }
    if (ref($h) =~ /HASH/ ) {
        foreach my $key (keys %$h) {
            $h->{$key} = filter_blessed($h->{$key});
        }
    }
    if ( ref($h) =~ /ARRAY/ ) {
        $h = [map {filter_blessed($_)} @$h];
    }
    return $h;
}
