The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.
use strict;
use warnings;

package App::backimap::Status;
BEGIN {
  $App::backimap::Status::VERSION = '0.00_13';
}
# ABSTRACT: manages backimap status

use Moose;
use MooseX::Storage;
with Storage( 'format' => 'JSON' );
# Storage prereq
use JSON::Any();
use version();

use English qw( -no_match_vars );


has timestamp => (
    is => 'ro',
    isa => 'Int',
    default => $BASETIME,
    required => 1,
);


has server => (
    is => 'ro',
    isa => 'Str',
    required => 1,
);


has user => (
    is => 'ro',
    isa => 'Str',
    required => 1,
);


has folder => (
    is => 'rw',
    isa => 'HashRef[App::backimap::Status::Folder]',
);


has storage => (
    is => 'ro',
    isa => 'App::backimap::Storage',
);

my $FILENAME = 'backimap.json';

# Extra status initialization is not documented in POD.

sub BUILD {
    my $self = shift;

    return unless $self->storage;

    if ( $self->storage->init ) {
        $self->save();
    }
    else {
        my $json = $self->storage->get($FILENAME);

        # Do not check package if version is alpha (CPAN: #68358)
        my %options;
        %options = ( check_version => '' )
            if version->parse( $self->VERSION )->is_alpha();

        my $status = App::backimap::Status->thaw( $json, %options );
        die "IMAP credentials do not match saved status\n"
            if $status->user ne $self->user ||
                $status->server ne $self->server;

        $self->folder( $status->folder )
            if $status->folder;
    }
}


sub save {
    my $self = shift;

    return unless $self->storage;

    my $json = $self->freeze();
    $self->storage->put( $FILENAME => $json );

    return 1;
}

1;

__END__
=pod

=head1 NAME

App::backimap::Status - manages backimap status

=head1 VERSION

version 0.00_13

=head1 ATTRIBUTES

=head2 timestamp

Time of last run started.

=head2 server

Server name used in IMAP.

=head2 user

User name used in IMAP.

=head2 folder

Collection of folder status.

=head2 storage

Object to use as the storage backend for status.

=head1 METHODS

=head2 save()

Save status to storage backend.

Returns true if status has actually a storage and saving was successful
or false otherwise.

=for Pod::Coverage BUILD

=head1 AUTHOR

Alex Muntada <alexm@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2011 by Alex Muntada.

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