#!perl
use Cassandane::Tiny;

sub test_mailbox_metadata_needs_read
    :needs_component_idled :NoAltNamespace
    ($self)
{
    $self->{instance}->add_start(name => 'idled', argv => [ 'idled' ]);
    $self->{instance}->start();

    my $svc = $self->{instance}->get_service('imap');
    my $admintalk = $svc->create_store(username => 'admin')->get_client();
    $admintalk->create("user.otheruser") or die "create: $@";
    $admintalk->create("user.otheruser.shared") or die "create: $@";
    $admintalk->setacl("user.otheruser.shared", "cassandane", "lr")
        or die "setacl: $@";

    my $store = $svc->create_store();
    my $talk = $store->get_client();
    $talk->_imap_cmd('NOTIFY', 0, "", "SET",
                     "(MAILBOXES (user.otheruser.shared INBOX)"
                     . " (MailboxMetadataChange))");
    $self->assert_str_equals('ok', $talk->get_last_completion_response());

    my @got;
    my %handlers = (metadata => sub { push @got, $_[1] });

    $admintalk->setmetadata('user.otheruser.shared', '/shared/comment', 'x');
    $self->assert_str_equals('ok', $admintalk->get_last_completion_response());
    $self->assert($store->idle_response(\%handlers, 10), "got METADATA");

    # RFC 5465 5: observed mailboxes need 'l' and 'r'.  INBOX, changed
    # afterwards, is the first response if the shared mailbox is skipped.
    $admintalk->setacl("user.otheruser.shared", "cassandane", "l")
        or die "setacl: $@";
    $admintalk->setmetadata('user.otheruser.shared', '/shared/comment', 'y');
    $self->assert_str_equals('ok', $admintalk->get_last_completion_response());
    $admintalk->setmetadata('user.cassandane', '/shared/comment', 'z');
    $self->assert_str_equals('ok', $admintalk->get_last_completion_response());
    $self->assert($store->idle_response(\%handlers, 10), "got METADATA");

    $self->assert_cmp_deeply([
        [ 'user.otheruser.shared', '/shared/comment' ],
        [ 'INBOX', '/shared/comment' ],
    ], \@got);
}
