#!perl
use Cassandane::Tiny;

sub test_using_storage_late
{
    my ($self) = @_;

    xlog $self, "test setting STORAGE quota resource after messages are added";

    $self->_set_quotaroot('user.cassandane');
    $self->_check_no_quota();
    my $talk = $self->{store}->get_client();

    $talk->create("INBOX.sub") || die "Failed to create subfolder";

    # append some messages
    my %expecteds = ();
    my $expected = 0;
    foreach my $folder ("INBOX", "INBOX.sub")
    {
        $expecteds{$folder} = 0;
        $self->{store}->set_folder($folder);

        for (1..10)
        {
            my $msg = $self->make_message("Message $_",
                                          extra_lines => 10 + rand(5000));
            my $len = length($msg->as_string());
            $expecteds{$folder} += $len;
            $expected += $len;
            xlog $self, "added $len bytes of message";
        }
    }

    $self->_set_limits(storage => 100000);
    $self->_check_usages(storage => int($expected/1024));
    $self->_check_smmap('cassandane', 'OK');

    # delete subfolder
    $talk->delete("INBOX.sub") || die "Failed to delete subfolder";
    $expected -= delete($expecteds{"INBOX.sub"});
    $self->_check_usages(storage => int($expected/1024));

    # delete messages
    $talk->select("INBOX");
    $talk->store('1:*', '+flags', '(\\deleted)');
    $talk->close();
    $expected -= delete($expecteds{"INBOX"});
    $self->assert_num_equals(0, $expected);
    $self->_check_usages(storage => int($expected/1024));
}
