#!perl
use Cassandane::Tiny;

sub test_card_set_create_calendars
    :min_version_3_9 :needs_dependency_icalvcard
{
    my ($self) = @_;
    my $jmap = $self->{jmap};

    my $service = $self->{instance}->get_service("http");
    $ENV{DEBUGDAV} = 1;
    my $carddav = Net::CardDAVTalk->new(
        user => 'cassandane',
        password => 'pass',
        host => $service->host(),
        port => $service->port(),
        scheme => 'http',
        url => '/',
        expandurl => 1,
    );

    my $id = 'ae2640cc-234a-4dd9-95cc-3106258445b9';

    my $res = $jmap->CallMethods([
        ['ContactCard/set', {
            create => {
                "1" => {
                    '@type' => 'Card',
                    version => '1.0',
                    uid => $id,
                    name => { full => 'Jane Doe' },
                    calendars => {
                        'CAL-1' => {
                            '@type' => 'CalendarResource',
                            kind => 'calendar',
                            uri => 'https://cal.example.com/calA',
                            pref => 1
                        },
                        'CAL-2' => {
                            '@type' => 'CalendarResource',
                            kind => 'calendar',
                            uri => 'https://ftp.example.com/calA.ics',
                            mediaType => 'text/calendar'
                        },
                        'FBURL-1' => {
                            '@type' => 'CalendarResource',
                            kind => 'freeBusy',
                            uri => 'https://www.example.com/busy/janedoe',
                            pref => 1
                        },
                        'FBURL-2' => {
                            '@type' => 'CalendarResource',
                            kind => 'freeBusy',
                            uri => 'https://example.com/busy/project-a.ifb',
                            mediaType => 'text/calendar'
                        }
                    }
                }
            }
        }, 'R1']
    ]);

    $self->assert_not_null($res->[0][1]{created}{1});

    my $href = $res->[0][1]{created}{1}{'cyrusimap.org:href'};
    $res = $carddav->Request('GET', $href, '',
                             'Accept' => 'text/vcard; version=4.0');

    my $card = $res->{content};
    $card =~ s/\r?\n[ \t]+//gs;  # unfold long properties

    $self->assert_matches(qr|CALURI;PROP-ID=CAL-1;PREF=1:https://cal.example.com/calA|, $card);
    $self->assert_matches(qr|CALURI;PROP-ID=CAL-2;MEDIATYPE=text/calendar:https://ftp.example.com/calA.ics|, $card);
    $self->assert_matches(qr|FBURL;PROP-ID=FBURL-1;PREF=1:https://www.example.com/busy/janedoe|, $card);
    $self->assert_matches(qr|FBURL;PROP-ID=FBURL-2;MEDIATYPE=text/calendar:https://example.com/busy/project-a.ifb|, $card);
    $self->assert_does_not_match(qr|JSPROP|, $card);
}
