#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use Getopt::Long;
use Text::Autoformat qw( form );
use WWW::Marvel::Client;
use WWW::Marvel::Config::File;

my $DEFAULT_CONF_FILE = 'marvel.conf';
my $OPT = commandline_options();
my ($character) = @ARGV;
if (!defined $character) {
	print "\nERROR: Undefined character name to search\n\n";
	print_help();
	exit 1;
}

my $cfg = WWW::Marvel::Config::File->new($OPT->{config});
my $client = WWW::Marvel::Client->new({
		public_key  => $cfg->get_public_key,
		private_key => $cfg->get_private_key,
	});

my $res = $client->characters({ name => $character });
# no valuable info in $res
my $data = $res->{data};

if ($data->{count} < 1) {
	print_hash($data);
	print "results: ", Dumper $data->{results};
	die "no result\n";
}
elsif ($data->{count} > 1) {
	print_hash($data);
	die "multiple results\n";
}

my %FMT = (
	name => q{  >>>>>>>>>>>> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< },
	desc => q{  >>>>>>>>>>>> [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ },
	li   => q{               * <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< },
);

my $result = $data->{results}->[0];
print_result($result);

sub print_result {
	my ($r) = @_;

	print form($FMT{name}, "Name:", $r->{name});
	print form($FMT{name}, "Id:", $r->{id});
	print form($FMT{name}, "Picture:", sprintf("%s.%s", $r->{thumbnail}->{path}, $r->{thumbnail}->{extension}));
	print form($FMT{desc}, "Description:", $r->{description});
	print form($FMT{name}, "Uri:", $r->{resourceURI});
	print "\n";

	my $urls = $r->{urls} // [];
	for my $u (sort { $a->{type} cmp $b->{type} } @$urls) {
		print form($FMT{desc}, ucfirst($u->{type}).':', $u->{url});
	}
	print "\n";

	print_collection('Comics',   $r->{comics})  if $OPT->{comics};
	print_collection('Events:',  $r->{events})  if $OPT->{events};
	print_collection('Series:',  $r->{series})  if $OPT->{series};
	print_collection('Stories:', $r->{stories}) if $OPT->{stories};
}

sub print_collection {
	my ($name, $c) = @_;
	print form($FMT{name}, $name, sprintf("%s/%s", $c->{returned}, $c->{available}));
	for my $i (@{ $c->{items} }) {
		print form($FMT{li}, $i->{name});
	}
	print form($FMT{name}, "Uri:", $c->{collectionURI});
	print "\n";
}

# urls : ARRAY(0x2b289e8)
# comics : HASH(0x2c3f790)
# events : HASH(0x2b273d8)
# series : HASH(0x320fca0)
# stories : HASH(0x2b269d0)
#	available : 11
# 	collectionURI : http://gateway.marvel.com/v1/public/characters/1009262/events
# 	returned : 11
# 	items : ARRAY(0x1b21e60)
#		name : Civil War
#		resourceURI : http://gateway.marvel.com/v1/public/events/238
#		...
#
# thumbnail : HASH(0x2c37c40)
#	extension : jpg
#	path : http://i.annihil.us/u/prod/marvel/i/mg/d/50/50febb79985ee
#
# description : Abandoned by his mother, Matt Murdock was raised by his father, boxer "Battling Jack" Murdock, in Hell's Kitchen. Realizing that rules were needed to prevent people from behaving badly, young Matt decided to study law; however, when he saved a man from an oncoming truck, it spilled a radioactive cargo that rendered Matt blind while enhancing his remaining senses. Under the harsh tutelage of blind martial arts master Stick, Matt mastered his heightened senses and became a formidable fighter.
# modified : 2013-07-01T16:44:00-0400
# resourceURI : http://gateway.marvel.com/v1/public/characters/1009262
# id : 1009262
# name : Daredevil

#for my $r (@$results) {
#	print $r->{name}, "\n";
#	print_hash($r);
#	last;
#}

sub commandline_options {
	my %opt = (
		config => $DEFAULT_CONF_FILE,
		comics => 0,
		events => 0,
		series => 0,
		stories => 0,
		help => 0,
	);
	GetOptions(\%opt, 'config=s', qw/ comics events series stories help /)
		or die "Error in cmdl args\n";

	if ($opt{help}) {
		print_help();
		exit 0;
	}

	return \%opt;
}

sub print_hash {
	my ($h) = @_;
	while (my ($k, $v) = each %$h) {
		print "$k : $v\n";
	}
}

sub print_help {
	print "Usage: $0 [OPTIONS] <character>\n";
	print "  OPTIONS:\n";
	print "    --comics        \t show comics\n";
	print "    --events        \t show events\n";
	print "    --series        \t show series\n";
	print "    --stories       \t show stories\n";
	print "    --config <file> \t Config file [$DEFAULT_CONF_FILE]\n";
	print "    --help          \t Show this help\n";
}
