#!/usr/bin/env perl
BEGIN {
  if (@ARGV and @ARGV[0] =~ /^\w/) {
    @ARGV = grep { (/^-{1,2}h\w{0,3}$/ ? ($ENV{APP_TT_HELP} = $ARGV[0], 0) : (1, 1))[1] } @ARGV;
  }
}

# Inspired by Mojo::File
package App::tt::file;
use strict;
use warnings;
use Cwd            ();
use File::Basename ();
use File::Find qw(find);
use File::Path ();
use File::Spec::Functions qw(canonpath catfile splitdir);
use JSON::XS ();
use overload '@{}' => sub { [splitdir ${$_[0]}] }, '""' => sub { ${$_[0]} }, fallback => 1;

sub new {
  my $class = shift;
  my $value = @_ == 1 ? $_[0] : @_ > 1 ? catfile @_ : canonpath(Cwd::getcwd());
  return bless \$value, ref $class || $class;
}

sub basename  { File::Basename::basename ${shift()}, @_ }
sub child     { $_[0]->new(${shift()}, @_) }
sub dirname   { $_[0]->new(scalar File::Basename::dirname ${$_[0]}) }
sub make_path { File::Path::make_path(${$_[0]}, @_); shift }

sub list_tree {
  my ($self, $cb) = (shift, shift);
  my %all;
  my $wanted = sub { $all{$File::Find::name}++ unless -d $File::Find::name };
  find {wanted => $wanted, no_chdir => 1}, $$self if -d $$self;
  delete $all{$$self};
  return map { my $f = $self->new(canonpath $_); $cb ? $cb->($f) : $f } sort keys %all;
}

sub slurp {
  my $self = shift;
  die qq{Can't open file "$self": $!} unless open my $file, '<', $$self;
  my $content = '';
  while ($file->sysread(my $buffer, 131072, 0)) { $content .= $buffer }
  $content =~ s!\s+$!!s;    # Remove newlines and extra space
  return $content;
}

sub spurt {
  my ($self, $content) = @_;
  die qq{Can't open file "$self": $!} unless open my $file, '>', $$self;
  die qq{Can't write to file "$self": $!} unless defined $file->syswrite($content);
  return $self;
}

package main;
use Applify;
use File::Temp ();
use File::HomeDir;
use List::Util qw(uniq);
use Scalar::Util qw(blessed);
use Time::Piece;
use Time::Seconds;

use constant DEBUG => $ENV{APP_TT_DEBUG} || 0;

option str => project     => 'Project name. Normally autodetected', alias => 'p';
option str => tag         => 'Tags for an event',                alias => 't', n_of => '@';
option str => description => 'Description for an event',         alias => 'd';
option str => group_by    => 'Group log output: --group-by day', alias => 'g';
option str => month       => 'Mass edit a month';
option str => year        => 'Mass edit a year';

documentation 'App::tt';
version 'App::tt';

our $PTY = -t STDOUT;
our $NOW = localtime;

$SIG{__DIE__} = sub { Carp::confess($_[0]) }
  if DEBUG;

# Attributes
sub root {
  shift->{root}
    //= App::tt::file->new($ENV{TT_HOME}
      || $ENV{TIMETRACKER_HOME}
      || (File::HomeDir->my_home, '.TimeTracker'));
}

sub command_edit {
  my $self = shift;
  return $self->_edit_with_editor($_[0]) if @_ and -f $_[0];    # Edit a given file
  return $self->_mass_edit(@_)           if $self->year or $self->month or !-t STDIN;
  return $self->_edit_with_editor;
}

sub command_export {
  my $self = shift;
  my $res  = $self->_log(@_);

  my @cols   = split /,/, $self->config('export_columns');
  my $format = join ',', map {'"%s"'} @cols;

  $res->{rounded} = 0;
  $self->_print($format, @cols);

  for my $event (sort { $a->{start} <=> $b->{start} } @{$res->{log}}) {
    $event->{date}  = $event->{start};
    $event->{hours} = int($event->{seconds} / 3600);
    $event->{seconds} -= $event->{hours} * 3600;
    $event->{minutes} = int($event->{seconds} / 60);
    $event->{rounded}
      = $event->{hours} + ($event->{minutes} >= $self->config('round_up_at') ? 1 : 0);
    $event->{hours} += sprintf '%.1f', $event->{minutes} / 60;
    $res->{rounded} += $event->{rounded};

    $self->_print(
      $format,
      map {
        my $val = $event->{$_} // '';
        $val = $val->ymd if blessed $val and $val->can('ymd');
        $val = join ',', @$val if ref $val eq 'ARRAY';
        $val =~ s!"!""!g;
        $val;
      } @cols
    );
  }

  $self->_print(
    '> Exact hours: %s. Rounded hours: %s Events: %s',
    $self->_duration($res->{seconds}, 'hm'),
    @$res{qw(rounded events)},
  );

  return 0;
}

sub command_help {
  my $self = shift;
  my $for  = shift || 'app';
  return $self->_script->print_help, 0 if $for eq 'app';

  my ($today, @help) = ($NOW->ymd);
  require App::tt;
  open my $POD, '<', $INC{'App/tt.pm'} or die "Cannot open App/tt.pm: $!";
  while (<$POD>) {
    s/\b2020-01-01(T\d+:)/$today$1/g;    # make "register" command easier to copy/paste
    push @help, $_ if /^=head2 $for/ ... /^=(head|cut)/;
  }

  shift @help;
  pop @help;                             # remove =head and =cut lines
  die "Could not find help for $for.\n" unless @help;
  $self->_print("@help");
  return 0;
}

sub command_log {
  my $self = shift;
  my $res  = $self->_log(@_);

  my @table = (['Month', 'Date', 'Start', 'Duration', 'Project', 'Tags'], '-');
  for my $event (sort { $a->{start} <=> $b->{start} } @{$res->{log}}) {
    my $start = $event->{start};
    push @table,
      [
      $start->month,
      sprintf('%2s', $start->mday),
      sprintf('%2s:%02s', $start->hour, $start->minute),
      $self->_duration($event->{seconds}, 'hm'),
      $event->{project} || '---',
      join(',', @{$event->{tags}}),
      ];
  }

  $res->{interval} eq 'month'
    ? $self->_print('> Log for %s %s', map { $res->{when}->$_ } qw(fullmonth year))
    : $self->_print('> Log for %s',    $res->{when}->year);
  push @table, '-' if @table > 3;
  $self->_print(\@table);

  @table = ();
  push @table, ['Total events', ':', $res->{events}];
  push @table, ['Total time',   ':', $self->_duration($res->{seconds}, 'hms')];

  my ($time_left, @time_left) = ('');
  if ($self->config('hours_per_month') and $res->{interval} eq 'month') {
    my ($days, $sec) = $self->_time_left($res);
    push @table, ['Remaining days', ':', $days > 0 ? $days : 0];
    push @table,
      ['Remaining time', ':', $self->_duration($sec / ($days <= 0 ? 1 : $days), '-hm') . '/day'];
  }

  $self->_print(\@table);

  return 0;
}

sub command_register {
  my ($self, $start, $stop) = @_;
  return $self->command_help('register') unless $start and $stop;

  $start = $self->_time(str => $start);
  $stop  = $self->_time(str => $stop, ref => $start);

  my %event = (
    __CLASS__   => 'App::TimeTracker::Data::Task',
    project     => $self->project || $self->config('project'),
    start       => $start,
    stop        => $stop,
    user        => scalar(getpwuid $<),
    tags        => [$self->_tags],
    description => $self->description,
  );

  my $trc_file = $self->_trc_path($event{project}, $start);
  if (-e $trc_file) {
    $self->_print("! $trc_file already exists.");
    return 1;
  }

  $self->_print('Registered %s at %s with duration %s.', @event{qw(project start duration)})
    if $self->_save(\%event);
  return $!;
}

sub command_start {
  my ($self, @args) = @_;

  my $event = {};
  $event->{start} = $self->_time(+(grep {/\d+\:/} @args)[0]);

  $event->{project} ||= $self->project;
  $event->{project} ||= (grep {/^[A-Za-z0-9-]+$/} @args)[0];
  $event->{project} ||= App::tt::file->new->basename if -d '.git';
  $event->{project} ||= $self->config('project');
  return $self->command_help('start') unless $event->{project};

  $self->_stop_previous(@args);
  return $! unless $self->_save($event);
  $self->root->child('previous')->spurt($event->{path});
  $self->_print('> Started working on project %s at %s.',
    $event->{project}, $event->{start}->hms(':'));
  return 0;
}

sub command_stop {
  my $self      = shift;
  my $exit_code = $self->_stop_previous(@_);
  $self->_print('! No previous event to stop.') if $exit_code == 3;
  return $exit_code;
}

sub command_status {
  my $self  = shift;
  my $event = $self->_get_previous_event;
  warn "[APP_TT] status $event->{path}\n" if DEBUG;

  if (!$event->{start}) {
    $self->_print('! No event is being tracked.');
    return 3;    # No such process
  }
  elsif ($event->{stop}) {
    $self->_print('> Stopped working on %s at %s after %s.',
      $event->{project}, $event->{stop}, $self->_duration($event->{seconds}));
    return 0;
  }
  else {
    my $duration = $NOW - $event->{start} + $NOW->tzoffset;
    $self->_print('> Been working on %s for %s.',
      $event->{project}, $self->_duration($duration, 'hms'));
    return 0;
  }
}

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

  unless ($self->{config}) {
    local %ENV = %ENV;
    for my $path ($self->root->child('config'), '.env') {
      next unless -r $path;
      open my $CONFIG, '<', $path or die qq{Can't open file "$path": $!};
      while (my $line = readline $CONFIG) {
        next unless $line =~ m!^(?:TT_)?(\w+)=(.+)!;
        $ENV{$1} = $2;
        $self->{config}{lc($1)} = $2;
      }
    }

    $self->{defaults} ||= {
      editor          => $ENV{EDITOR}             || 'nano',
      export_columns  => $ENV{TT_COLUMNS}         || 'date,project,hours,rounded,tags,description',
      hours_per_month => $ENV{TT_HOURS_PER_MONTH} || 0,
      min_time        => $ENV{TT_MIN_TIME}        || 300,
      round_up_at     => $ENV{TT_ROUND_UP_AT}     || 30,
    };
  }

  return $self->{config}{$key} // $self->{defaults}{$key} // die "Missing option '$key'.\n";
}

sub _edit_with_editor {
  my ($self,  $trc_file) = @_;
  my ($event, $prev) = $trc_file ? ($self->_load($trc_file), 0) : ($self->_get_previous_event, 1);

  $trc_file = $event->{path} //= 'Not found';
  die "Could not find file to edit. ($event->{path})\n" unless $event->{start};

  my $fh = File::Temp->new;
  printf $fh "# %s\n", $event->{path};
  for my $k (qw(project tags description start stop user)) {
    $event->{$k} = join ', ', @{$event->{$k} || []} if $k eq 'tags';
    $event->{$k} = $event->{$k}->datetime if $k eq 'start' or $k eq 'stop' and $event->{$k};
    printf $fh "%-12s %s\n", "$k:", $event->{$k} // '';
  }

  close $fh;
  $self->_print("Edit $event->{path}");
  system $self->config('editor') => "$fh";

  for (split /\n/, App::tt::file->new("$fh")->slurp) {
    my ($k, $v) = /^(\w+)\s*:\s*(.+)/ or next;
    $v           = [grep {length} split /[\s,]+/, $v] if $k eq 'tags';
    $v           = $self->_time(str => $v)                         if $k eq 'start';
    $v           = $self->_time(str => $v, ref => $event->{start}) if $k eq 'stop';
    $event->{$k} = $v;
  }

  return $! unless $self->_save($event);
  $self->root->child('previous')->spurt($event->{path}) if $prev;
  unlink $trc_file or die "rm $trc_file: $!" unless $trc_file eq $event->{path};
  return 0;
}

sub _print {
  my ($self, $data, @args) = @_;

  if (ref $data eq 'ARRAY') {
    my $th     = $data->[0][-1] eq '{X}' ? 1    : 0;
    my @margin = $PTY                    ? ('') : ();
    my ($width, @lines, @spec);

    for my $row (@$data) {
      push @lines, $row and next unless ref $row eq 'ARRAY';
      my $w = 0;
      for my $col (0 .. $#$row) {
        ($row->[$col] //= '') =~ y/\r\n//d;
        my $len = length $row->[$col];
        $spec[$col] = $len if $len >= ($spec[$col] // 0);
        $w += $spec[$col] + 2;
      }
      $width = $w if $w >= ($width // 0);
    }

    $width -= 2;
    my @fm = (map({"\%-${_}s"} @spec[0 .. $#spec - 1]), '%s');
    $data = join '', map {
      ref $_
        ? sprintf join('  ', @margin, @fm[0 .. $#$_]) . "\n", @$_
        : '  ' . ($_ x $width) . "\n";
    } @$data;
  }

  my $fh = \*STDOUT;
  if ($data =~ s/^(>|!)\s//) {
    my $type = $1;
    $fh   = \*STDERR;
    $data = "\n$data\n";
    $data =~ s!\n!\n  !g if $PTY;
  }

  return print {$fh} "$data\n" if @_ == 2;
  return printf {$fh} "$data\n", @args;
}

sub _fill_log_days {
  my ($self, $last, $now) = @_;
  my $interval = int(($now - $last)->days);

  map {
    my $t = $last + $_ * 86400;
    +{seconds => 0, start => $t, tags => [$t->day]}
  } 1 .. $interval;
}

sub _get_previous_event {
  my $self     = shift;
  my $previous = $self->root->child('previous');
  my $trc_file = -r $previous
    && App::tt::file->new($previous->slurp);    # $ROOT/previous contains path to last .trc file
  return $trc_file && -r $trc_file ? $self->_load($trc_file) : {path => $trc_file};
}

sub _group_by_day {
  my ($self, $res) = @_;
  my $pl = 0;
  my %log;

  for my $e (@{$res->{log}}) {
    my $k = $e->{start}->ymd;
    $log{$k} ||= {%$e, seconds => 0};
    $log{$k}{seconds} += $e->{seconds};
    $log{$k}{_project}{$e->{project}} = 1;
    $log{$k}{_tags}{$_} = 1 for @{$e->{tags}};
  }

  $res->{log} = [
    map {
      my $p = join ', ', keys %{$_->{_project}};
      $pl = length $p if $pl < length $p;
      +{%$_, project => $p, tags => [keys %{$_->{_tags}}]};
    } map { $log{$_} } sort keys %log
  ];
}

sub _duration {
  my ($self, $duration, $sep) = @_;
  my $seconds = int(ref $duration ? $duration->seconds : $duration);
  my ($hours, $minutes);

  $hours = int($seconds / 3600);
  $seconds -= $hours * 3600;
  $minutes = int($seconds / 60);
  $seconds -= $minutes * 60;

  return sprintf '%s:%02s:%02s', $hours, $minutes, $seconds if !$sep;
  return sprintf '%s:%02s',      $hours, $minutes if $sep eq '-hm';
  return sprintf '%2s:%02s',     $hours, $minutes if $sep eq 'hm';
  return sprintf '%sh %sm %ss',  $hours, $minutes, $seconds;
}

sub _load {
  my ($self, $path) = @_;
  my $event = JSON::XS::decode_json($path->slurp);
  $event->{path} = $path;
  $event->{tags} = [map { split /\s*,\s*/, $_ } @{$event->{tags} || []}];
  $event->{$_}   = $self->_time($event->{$_}) for grep { $event->{$_} } qw(start stop);
  return $event;
}

sub _log {
  my $self       = shift;
  my $tags       = join ',', $self->_tags;
  my @project_re = map {qr{^$_\b}} split /,/, $self->project || '.+';

  my $res = {events => 0, log => [], seconds => 0};

  for (@_) {
    /^(-\d+)(m|y|month|year)$/ and ($res->{start_at} = $1 and $res->{interval} = $2);
    /^(-\d+)$/      and $res->{start_at} ||= $1;
    /^(month|year)/ and $res->{interval} ||= $1;
    /^--fill/       and $res->{fill}     ||= 1;
  }

  $res->{fill}     ||= 0;
  $res->{interval} ||= 'month';
  $res->{start_at} ||= 0;

  if ($res->{interval} =~ m!^y!) {
    $res->{when} = $self->_time(Y => $NOW->year + $res->{start_at}, m => 1, d => 1);
    $res->{path} = $self->root->child($res->{when}->year);
  }
  else {
    $res->{when} = $self->_time(m => $NOW->mon + $res->{start_at}, d => 1);
    $res->{path} = $self->root->child($res->{when}->year, sprintf '%02s', $res->{when}->mon);
  }

  $res->{path}->list_tree(sub {
    my $file = shift;
    return unless my ($date, $hms, $project) = $file->basename =~ m!^(\d+)-(\d+)_(.*)\.trc$!;
    my $event = $self->_load($file);
    return if @project_re and !grep { $event->{project} =~ $_ } @project_re;
    return if $tags       and !grep { $tags             =~ /\b$_\b/ } @{$event->{tags}};
    $event->{stop}    ||= $NOW + $NOW->tzoffset;
    $event->{seconds} ||= $event->{stop} - $event->{start};
    push @{$res->{log}},
      $self->_fill_log_days(@{$res->{log}} ? $res->{log}[-1]{start} : $res->{when}, $event->{start})
      if $res->{fill};
    pop @{$res->{log}}
      if @{$res->{log}}
      and !$res->{log}[-1]{project}
      and $res->{log}[-1]{start}->mday == $event->{start}->mday;
    push @{$res->{log}}, $event;
    $res->{events}++;
    $res->{seconds} += $event->{seconds};
  });

  if (my $method = $self->can(sprintf '_group_by_%s', $self->group_by || 'nothing')) {
    $self->$method($res);
  }

  return $res;
}

sub _mass_edit {
  my $self = shift;

  $self->year($NOW->year) if $self->month and !$self->year;
  my $path = $self->root;
  $path = App::tt::file->new($path, $self->year) if $self->year;
  $path = App::tt::file->new($path, sprintf '%02s', $self->month) if $self->month;

  my $re = '';
  $re .= sprintf '(%s)',   $self->year  || '\d{4}';    # (year)     = ($1)
  $re .= sprintf '(%02s)', $self->month || '\d{2}';    # (month)    = ($2)
  $re .= '(\d{2})-(\d+)_';                             # (day, hms) = ($3, $4)
  $re .= sprintf '(%s)', $self->project || '[^.]+';    # (project)  = ($5)
  $re .= '\.trc';

  # Edit all files with code from STDIN
  my $code = '';
  if (!-t STDIN or !($self->year or $self->month)) {
    $code .= $_ while <STDIN>;
    $code = "sub {$code}" unless $code =~ /^\s*sub\b/s;
    $code = eval "use 5.10.1;use strict;use warnings;$code"
      or die "Could not compile code from STDIN: $@\n";
  }

  $path->list_tree(sub {
    my %info = (file => shift);
    return unless $info{file} =~ m!^$re$!;
    @info{qw(year month day date hms project)} = ($1, $2, $3, "$1$2$3", $4, $5);
    $self->command_edit($info{file}), next unless $code;
    my $event = $self->_load($info{file});
    local %_ = %info;
    $self->_save($event) if $code and $self->$code($event);
    unlink $info{file} or die "rm $info{file}: $!" unless $info{file} eq $event->{path};
  });

  return 0;
}

sub _save {
  my ($self, $event) = @_;

  $event->{__CLASS__}   ||= 'App::TimeTracker::Data::Task';
  $event->{description} ||= $self->description // '';
  $event->{project}     ||= $self->project || $self->config('project');
  $event->{seconds}     ||= 0;
  $event->{tags}        ||= [uniq @{$event->{tags} || []}, $self->_tags];
  $event->{user}        ||= scalar(getpwuid $<);

  if (my $duration = $event->{stop} && $event->{start} && $event->{stop} - $event->{start}) {
    $event->{seconds} = $duration->seconds;
  }
  if ($event->{stop} and $event->{seconds} < $self->config('min_time')) {
    $self->_print('! Too short duration (%s)', $self->_duration($event->{duration}));
    $! = 52;
    return 0;
  }

  $event->{duration} = $self->_duration($event->{seconds});   # Used by App::TimeTracker::Data::Task

  my %event = %$event;
  delete $event{path};
  $event{start} = $event->{start}->datetime if $event->{start};
  $event{stop}  = $event->{stop}->datetime  if $event->{stop};

  $event->{path} = $self->_trc_path($event->{project}, $event->{start});
  $event->{path}->dirname->make_path unless -d $event->{path}->dirname;
  $event->{path}->spurt(JSON::XS::encode_json(\%event));
  return 1;
}

sub _tags {
  my $self = shift;
  return $self->tag(shift) if @_;
  return uniq map { split /,/, $_ } @{$self->tag || []};
}

sub _stop_previous {
  my ($self, @args) = @_;

  my $event = $self->_get_previous_event;
  return 3 if !$event->{start} or $event->{stop};    # 3 == No such process

  $event->{stop} = $self->_time(+(grep {/\d+\:/} @args)[0]);

  my $duration = $event->{stop} - $event->{start};
  if ($duration->seconds < $self->config('min_time')) {
    $self->_print(
      qq(! Dropping log event for %s since worked less than @{[$self->config('min_time')]}s.),
      $event->{project});
    unlink $event->{path} or die "rm $event->{path}: $!";
    return 52;
  }

  if ($self->_save($event)) {
    $self->_print('> Stopped working on %s after %s.',
      $event->{project}, $self->_duration($duration, 'hms'));
    return 0;
  }

  return $! || 1;
}

sub _time {
  my $self = shift;
  my %t    = @_ == 1 ? (str => shift) : (@_);

  if ($t{str}) {
    my ($ymd, $hms) = split /[T\s]/, $t{str};
    ($hms, $ymd) = ($ymd, '') if !$hms and $ymd =~ m!:!;
    $t{Y} = $1 if $ymd =~ s!(\d{4})!!;
    $t{m} = $1 if $ymd =~ s!0?(\d{1,2})-(\d+)!$2!;
    $t{d} = $1 if $ymd =~ s!0?(\d{1,2})!!;
    $t{H} = $1 if $hms =~ s!0?(\d{1,2})!!;
    $t{M} = $1 if $hms =~ s!0?(\d{1,2})!!;
    $t{S} = $1 if $hms =~ s!0?(\d{1,2})!!;
  }

  my $ref = $t{ref} || $NOW;
  $ref = $self->_time($ref) unless ref $ref;
  $t{Y} ||= $ref->year;
  $t{m} //= $ref->mon;
  $t{d} //= $ref->mday;
  $t{S} //= defined $t{H} || defined $t{M} ? 0 : $ref->second;
  $t{M} //= defined $t{H}                  ? 0 : $ref->min;
  $t{H} //= $ref->hour;

  @t{qw(m Y)} = (12 - $t{m}, $t{Y} - 1) if $t{m} <= 0;
  @t{qw(m Y)} = (1, $t{Y} + 1) if $t{m} > 12;

  eval {
    $t{iso} = sprintf '%s-%02s-%02sT%02s:%02s:%02s', @t{qw(Y m d H M S)};
    $t{tp}  = Time::Piece->strptime("$t{iso}+0000", '%Y-%m-%dT%H:%M:%S%z');
  } or do {
    $@ =~ s!\r?\n$!!;
    $@ =~ s!\sat\s\W+.*!! unless DEBUG;
    die "Invalid time: $t{str} ($t{iso}): $@\n" if $t{str};
    die "Invalid time: $t{iso}: $@\n";
  };

  return $t{tp};
}

sub _time_left {
  my ($self, $res) = @_;
  my $start       = $self->_time(d => 1, H => 0, M => 0, S => 0);
  my $end         = $self->_time(d => 1, m => $start->mon + 1, H => 0, M => 0, S => 0);
  my $total_days  = 0;
  my $worked_days = 0;
  while ($start < $end) {
    if ($start->day_of_week != 0 and $start->day_of_week != 6) {
      $worked_days++ if $start < $NOW;
      $total_days++;
    }
    $start += ONE_DAY;
  }

  my $remaining_days    = $total_days - $worked_days + ($NOW->hour > 12 ? 0 : 1);
  my $total_seconds     = $self->config('hours_per_month') * 3600;
  my $remaining_seconds = $total_seconds - $res->{seconds};
  return $remaining_days, $remaining_seconds;
}

sub _trc_path {
  my ($self, $project, $t) = @_;
  my $month = sprintf '%02s', $t->mon;
  my $file;

  $project =~ s!\W!_!g;
  $file = sprintf '%s-%s_%s.trc', $t->ymd(''), $t->hms(''), $project;

  return $self->root->child($t->year, $month, $file);
}

app {
  my ($self, $command) = (shift, shift);
  return $self->command_help($ENV{APP_TT_HELP}) if $ENV{APP_TT_HELP};
  return $self->command_status(@_)              if !$command or $command eq 'status';
  my $method = $self->can("command_$command");
  return $self->$method(@_) if $method;
  die qq(Unknown command "$command".\n);
};
