package Bookmark;

use Moose;
use HTTP::Date qw{time2isoz};

has id    => ( is => 'ro' );
has uri   => ( is => 'rw' );
has title => ( is => 'rw' );
has ctime => ( is => 'ro' );
has mtime => (
    is => 'ro',
    # mtime defaults to ctime
    default => sub { $_[0]->ctime },
    lazy => 1,
);
has tags  => ( is => 'rw' );
has bookmark_uri => ( is => 'rw' );
has exists => ( is => 'ro' );
has collection => ( is => 'ro' );

sub created { scalar localtime $_[0]->ctime }
sub updated { scalar localtime $_[0]->mtime }
sub created_iso { (my $iso = time2isoz($_[0]->ctime)) =~ s/\D//g; return $iso; }
sub updated_iso { (my $iso = time2isoz($_[0]->ctime)) =~ s/\D//g; return $iso; }

sub BUILD {
    my $self = shift;
    my $args = shift;
    if ($args->{base_uri}) {
        $self->bookmark_uri(URI->new_abs($self->id, $args->{base_uri}));
    }
}

sub to_hashref {
    my $self = shift;
    return {
        id    => $self->id,
        uri   => $self->uri,
        title => $self->title,
        ctime => $self->ctime,
        mtime => $self->mtime,
        tags  => $self->tags,
        ($self->bookmark_uri ? (bookmark_uri => $self->bookmark_uri->canonical->as_string) : ()),
    };
}

sub update {
    my $self = shift;
    die "Not part of a collection; nowhere to write this bookmark" unless $self->collection;
    return $self->collection->update($self);
}

# module return
1;
