#!/usr/bin/env perl
# PODNAME: dump_fitbit_data_to_csv
# ABSTRACT: dump the last week's worth of FitBit data to a CSV file.
use strictures 1;
use 5.010;

use autodie;
use POSIX;
use Text::CSV;
use WebService::FitBit;

my $file = shift
  or die "Provide file name to dump data into.";

open( my $OUT , '>:encoding(utf8)' , $file );

my $fb = WebService::FitBit->new();

my @days = get_day_list();

my @header =  qw{
                  DATE
                  BURNED
                  CONSUMED
                  SCORE
                  STEPS
                  DISTANCE
                  ACTIVE_VERY
                  ACTIVE_FAIR
                  ACTIVE_LIGHT
                  SLEEP_TIME
                  AWOKEN
              };

my $csv = Text::CSV->new({ binary => 1 , eol => "\n" });
$csv->print( $OUT , \@header );

for my $date ( @days ) {
  say "Dumping $date";

  my $minutes_active = $fb->minutes_active($date);

  my @row = (
    $date ,
    $fb->calories_burned($date) ,
    $fb->calories_consumed($date) ,
    $fb->active_score($date) ,
    $fb->steps_taken($date) ,
    $fb->distance_from_steps($date) ,
    $minutes_active->{very} ,
    $minutes_active->{fairly} ,
    $minutes_active->{lightly} ,
    $fb->time_asleep($date) ,
    $fb->times_woken_up($date) ,
  );

  $csv->print( $OUT , \@row );
}

close( $OUT );

sub get_day_list {
  my $today = time;

  my @days;

  for ( 1 .. 7 ) {
    push @days , strftime( "%F" , localtime($today));
    $today -= 86400; # 1 day in seconds
  }

  return reverse @days;
}

__END__
=pod

=head1 NAME

dump_fitbit_data_to_csv - dump the last week's worth of FitBit data to a CSV file.

=head1 VERSION

version 0.1_3

=head1 AUTHORS

=over 4

=item *

John SJ Anderson <genehack@genehack.org>

=item *

Eric Blue <ericblue76@gmail.com>

=back

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2010 by John SJ Anderson.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut

