package App::bif::work;
use strict;
use warnings;
use Bif::Mo;
use DBIx::ThinSQL qw/concat coalesce qv/;
use IO::Prompt::Tiny qw/prompt/;
use Time::Piece;

our $VERSION = '0.1.5_7';
extends 'App::bif';

sub run {
    my $self = shift;
    my $opts = $self->opts;
    my $work = $self->current_work;
    my $dbw  = $self->dbw;

    # Nothing specified, just display the status
    if ( !exists $opts->{id} ) {
        if ($work) {
            if ( $work->{kind} eq 'topic' ) {
                printf "working %s %s %s (since %s)\n  (%s)\n", $work->{kind},
                  $work->{path},
                  $self->s2hm( time - $work->{start} ),
                  localtime( $work->{start} )->strftime('%Y-%m-%d %H:%M:%S'),
                  $work->{title};
            }
            else {
                printf "working %s %s %s (since %s)\n", $work->{kind},
                  $work->{path},
                  $self->s2hm( time - $work->{start} ),
                  localtime( $work->{start} )->strftime('%Y-%m-%d %H:%M:%S'),
                  ;
            }
            return $self->ok('Working');
        }
        print "Not currently working a node.\n";
        return $self->ok('NoWork');
    }

    my $epoch = $self->datetime2s( $opts->{at} );

    return $dbw->txn(
        sub {
            # Stop work if we were actually working
            if ($work) {
                $self->stop_work(
                    bill    => $opts->{bill},
                    stop    => $epoch,
                    comment => $opts->{comment},
                );

                printf "stopped working %s %s after %s\n", $work->{kind},
                  $work->{path},
                  $self->s2hm( $epoch - $work->{start} );
                return $self->ok('StopWork') if $opts->{id} eq '-';
            }

            if ( $opts->{id} eq '-' ) {

                print "Not currently working a node.\n";
                return $self->ok('NoWork');
            }

            # Check validity of ID
            my $info = $self->get_node( $opts->{id} );
            $opts->{id} = $info->{id};

            # Maybe complain if we are working something else
            if ($work) {
                return $self->err(
                    'WorkOther',   "working %s %s [%s] since %s",
                    $work->{kind}, $work->{node_id},
                    $work->{path}, scalar localtime( $work->{start} )
                ) unless $opts->{force};

                $opts->{comment} ||= prompt( 'Comment:', '' );
                $self->stop_work( stop => $epoch - 1 );
                printf "stopped working %s %s after %s\n", $work->{kind},
                  $work->{path},
                  $self->s2hm( $epoch - $work->{start} );
            }
            else {
                $opts->{comment} ||= prompt( 'Comment:', '' );
            }

            # Finally, start the new work

            $self->start_work(
                node_id => $info->{id},
                start   => $epoch,
                comment => $opts->{comment},
                bill    => $opts->{bill},
            );

            $work = $self->current_work;

            printf "working %s %s since %s\n", $work->{kind},
              $work->{path},
              scalar localtime( $work->{start} );

            return $self->ok('StartWork');
        }
    );

}

1;
__END__

=for bif-doc #timesheet

=head1 NAME

bif-work - track your work on a node

=head1 VERSION

0.1.5_7 (2015-11-25)

=head1 SYNOPSIS

    bif work [ID] [COMMENT...] [OPTIONS...]

=head1 DESCRIPTION

The C<bif-work> command is used to record time spent working on a node.

When ID is a valid node ID then work starts. When ID is a dash '-' then
work stops. With no arguments C<bif-work> prints the current work
status.

A COMMENT is required when starting work (will be prompted for if not
given) and may also be provided when stopping work. Attempting to start
work when you are already working a node fails unless the C<--force>
option is used.

B<NOTE:> the work buffer is B<not synchronized> with any hub and will
therefore be lost if you delete your local repository. The cumulative
time worked is however recorded during node updates.

=head1 ARGUMENTS & OPTIONS

=over

=item ID

A node ID, project PATH, or a single dash "-".

=item COMMENT

A comment to record with the starting or stopping of work.

=item --at, -a

Start or stop time in format "[yyyy-mm-dd] hh:mm[:ss]". Will also
accept the string "yesterday" in place of "yyyy-mm-dd".

=item --force, -f

Force the working of a node even when currently working.

=item --not-bill, -B

Do not record this work entry in the next update.

=item --uuid, -U

Lookup the node using ID as a UUID string instead of a node integer.

=back

=head1 SEE ALSO

L<bif>(1), L<bif-log-work>

=head1 AUTHOR

Mark Lawrence E<lt>nomad@null.netE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright 2015 Mark Lawrence <nomad@null.net>

This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.

