package shell;

use warnings;
use strict;

use autodie;
use Data::Dump qw/dump/;
use CouchDB;

our $command;

sub command {
	( undef, $command ) = @_;
	__PACKAGE__;
}

sub lines {
	my ( $self, $key ) = @_;

warn "command $command key $key";

	my $info;

	my @header;

	my $split_re;

	open(my $brctl, '-|', $command);
	while(<$brctl>) {
		chomp;

		if ( ! $split_re ) {
			$split_re = qr/\t+/ if m/\t/;
			$split_re ||= qr/\s+/ if m/\s/;
		}

		my @cols = split( $split_re, $_);

		if ( ! @header ) {
			@header = @cols;
			$info->{_header} = [ @header ] if $key;
			next;
		}

		my $hash =  { map { ( $header[$_] => $cols[$_] ) } 0 .. $#cols } ;

		if ( $key ) {
			my $k = $cols[$key - 1];
			$info->{$k} = $hash;
			CouchDB::audit( $command, $k, $hash );
		} else {
			push @$info, $hash;
		}

	}

	warn $command, ' ', dump( $info );

	return $info;
}

sub hash_by { lines(@_) }

1;
