#!/usr/bin/env perl

use strict;
use warnings;

use MYDan::Node;
use MYDan::Util::OptConf;

$| ++;

my $option = MYDan::Util::OptConf->load();
my %o = $option->get( qw( list count show dump ) )->dump();

my $cluster = MYDan::Node->new( $option->dump( 'range' ) );
my $range = MYDan::Node->new();
my $output;

map { $range->add( $cluster->load( $_ ) ) }
    @ARGV, -t STDIN ? () : map { split /\s+/ } <STDIN>;

=head1 SYNOPSIS

=head3 list

Print range as a random list.

$0 expr .. --list

=cut
if ( $o{list} ) { $output = join "\n", $range->list() }

=head3 count

$0 expr .. --count

=cut
elsif ( $o{count} ) { $output = $range->list() }

=head3 count

$0 expr .. --show

=cut

elsif ( $o{show} ) 
{ 
    my %t; map{ $_ =~ /(\w+\.\w+\.[a-z]+)$/; push @{$t{$1||'unknow'}}, $_; }$range->list();
    map{
        printf "$_ [%s]:%s\n", 
            scalar $range->load( $t{$_} )->list(), $range->load( $t{$_} )->dump;
    }keys %t;
    exit 0;
}

elsif( $o{dump} )
{
    my @d = $range->list();
    my %c = @d ? ( name => [ 1, @d ] ): ();
    my @r = $cluster->db()->select( 'name,attr,node,info', %c ); 

    my %r; map{ $r{$_->[0]}{$_->[1]}{$_->[2]}= $_->[3]}@r;
    print STDOUT YAML::XS::Dump \%r;
    exit 0;
}
=head3 normalize

Print a range expression

$0 expr ..

=cut
else { $output = $range->dump() }

print "$output\n";
exit 0;