#!perl
use Cassandane::Tiny;

sub test_calendar_set_shared_sort_order
    :min_version_3_9
{
    my ($self) = @_;
    my $jmap = $self->{jmap};
    my $caldav = $self->{caldav};
    my $admintalk = $self->{adminstore}->get_client();
    my $service = $self->{instance}->get_service("http");
    my ($maj, $min) = Cassandane::Instance->get_version();

    xlog $self, "create shared account";
    $admintalk->create("user.manifold");

    my $mantalk = Net::CalDAVTalk->new(
        user => "manifold",
        password => 'pass',
        host => $service->host(),
        port => $service->port(),
        scheme => 'http',
        url => '/',
        expandurl => 1,
    );

    $admintalk->setacl("user.manifold", admin => 'lrswipkxtecdan');
    $admintalk->setacl("user.manifold", manifold => 'lrswipkxtecdn');

    xlog $self, "create calendars";
    my $CalendarId1 = $mantalk->NewCalendar({name => 'Manifold Calendar1'});
    $self->assert_not_null($CalendarId1);
    my $CalendarId2 = $mantalk->NewCalendar({name => 'Manifold Calendar2'});
    $self->assert_not_null($CalendarId2);

    xlog $self, "share $CalendarId1 and $CalendarId2 read-only to user";
    $admintalk->setacl("user.manifold.#calendars.$CalendarId1", "cassandane" => 'lrw') or die;
    $admintalk->setacl("user.manifold.#calendars.$CalendarId2", "cassandane" => 'lrw') or die;

    xlog $self, "Verify shared account is NOT isReadOnly";
    my $RawRequest = {
        headers => {
            'Authorization' => $jmap->auth_header(),
        },
        content => '',
    };
    my $RawResponse = $jmap->ua->get($jmap->uri(), $RawRequest);
    $self->assert_str_equals('200', $RawResponse->{status});
    my $session = eval { decode_json($RawResponse->{content}) };
    $self->assert_equals(JSON::false, $session->{accounts}{manifold}{isReadOnly});

    xlog $self, "Set sortOrder on a calendar";
    my $res = $jmap->CallMethods([
            ['Calendar/set', {
                    accountId => 'manifold',
                    update => {
                        $CalendarId1 => {
                            sortOrder => 2
                        }
                    }
             }, "R1"]
    ]);
    $self->assert(exists $res->[0][1]{updated}{$CalendarId1});
}
