#!perl
use Cassandane::Tiny;

sub test_blob_get
    :min_version_3_5 :needs_component_jmap :JMAPExtensions
{
    my $self = shift;
    my $jmap = $self->{jmap};

    my $store = $self->{store};
    my $talk = $store->get_client();
    my $inbox = 'INBOX';

    xlog $self, "Generate an email in $inbox via IMAP";
    my %exp_sub;
    $store->set_folder($inbox);
    $store->_select();
    $self->{gen}->set_next_uid(1);

    my $body = "A plain text email.";
    $exp_sub{A} = $self->make_message("foo",
        body => $body
    );

    xlog $self, "get email list";
    my $res = $jmap->CallMethods([['Email/query', {}, "R1"]]);
    my $ids = $res->[0][1]->{ids};

    xlog $self, "get emails";
    $res = $jmap->CallMethods([['Email/get', { ids => $ids }, "R1"]]);
    my $msg = $res->[0][1]{list}[0];

    my $blobId = $msg->{textBody}[0]{blobId};
    $self->assert_not_null($blobId);

    xlog "Test without capability";
    $res = $jmap->CallMethods([['Blob/get', { ids => [$blobId], properties => [ 'data:asText', 'size' ] }, 'R1']]);
    $self->assert_str_equals($res->[0][0], 'error');

    # XXX: this will be replaced with the upstream one
    $jmap->AddUsing('https://cyrusimap.org/ns/jmap/blob');

    xlog "Regular Blob/get works and returns a blobId";
    $res = $jmap->CallMethods([['Blob/get', { ids => [$blobId], properties => [ 'data:asText', 'data:asBase64', 'size' ] }, 'R1']]);
    $self->assert_str_equals($res->[0][0], 'Blob/get');
    $self->assert_num_equals(1, scalar @{$res->[0][1]{list}});
    $self->assert_str_equals($blobId, $res->[0][1]{list}[0]{id});
    $self->assert_str_equals($body, $res->[0][1]{list}[0]{'data:asText'});
    $self->assert_str_equals(encode_base64($body, ''), $res->[0][1]{list}[0]{'data:asBase64'});
    $self->assert_num_equals(length($body), $res->[0][1]{list}[0]{'size'});
}
