#!perl
use Cassandane::Tiny;

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

    xlog $self, "testing RFC5257 SORT command ANNOTATION order criterion";

    my $entry = '/comment';
    my $attrib = 'value.priv';
    # 20 random dictionary words
    my @values = ( qw(gradual flips tempe cud flaunt nina crackle congo),
                   qw(buttons coating byrd arise ayyubid badgers argosy),
                   qw(sutton dallied belled fondues mimi) );
    # the expected result of sorting those words alphabetically
    my @exp_order = ( 15, 12, 13, 14, 18, 9, 11, 10, 8,
                      7, 4, 17, 5, 2, 19, 1, 20, 6, 16, 3 );

    $self->{store}->set_fetch_attributes('uid', "annotation ($entry $attrib)");

    xlog $self, "Append some messages and store annotations";
    my %exp;
    for (my $i = 0 ; $i < 20 ; $i++)
    {
        my $letter = chr(ord('A')+$i);
        my $uid = $i+1;
        my $value = $values[$i];

        $exp{$letter} = $self->make_message("Message $letter");
        $self->set_msg_annotation(undef, $uid, $entry, $attrib, $value);
        $exp{$letter}->set_attribute('uid', $uid);
        $exp{$letter}->set_annotation($entry, $attrib, $value);
    }
    $self->check_messages(\%exp);

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

    xlog $self, "run the SORT command with an ANNOTATION order criterion";
    my $res = $talk->sort("(ANNOTATION $entry $attrib)", 'utf-8', 'all');
    $self->assert_str_equals('ok', $talk->get_last_completion_response());
    $self->assert_not_null($res);
    $self->assert_deep_equals(\@exp_order, $res);
}
