package Counter;
use Moose;
use Moose::Util::TypeConstraints;
use MooseX::Storage;
use MooseX::AttributeHelpers;

use DateTime;
use DateTime::Format::MySQL;

class_type 'DateTime';

with Storage('format' => 'JSON', 'io' => 'AtomicFile');

has 'counter' => (metaclass => 'Counter', default => 1);

has 'date' => (
    is      => 'rw',
    isa     => 'DateTime',
    default => sub { DateTime->now },
);

sub reset_date {
    (shift)->date(DateTime->now)
}

sub to_string {
    my $self = shift;
    $self->counter . " hit(s) since " . $self->date->strftime("%A %B %d, %Y at %I:%M %p");
}

MooseX::Storage::Engine->add_custom_type_handler(
    'DateTime' => (
        expand   => sub {
            my ($date_string) = @_;
            DateTime::Format::MySQL->parse_datetime($date_string);
        },
        collapse => sub {
            my ($date_obj) = @_;
            DateTime::Format::MySQL->format_datetime($date_obj)
        }
    )
);

1;