#!perl
use Cassandane::Tiny;

sub test_card_set_create_basic
    :min_version_3_9 :needs_component_jmap :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,
    );

    xlog $self, "create addressbook";
    my $res = $jmap->CallMethods([
            ['AddressBook/set', { create => { "1" => {
                            name => "foo"
             }}}, "R1"]
    ]);

    my $abookid = $res->[0][1]{created}{"1"}{id};

    my $now = DateTime->now();
    my $created = $now->strftime('%Y-%m-%dT%H:%M:%SZ');
    my $prodid = '-//Example Corp.//CardDAV Client//EN';
    my $name = 'Mr. John Q. Public, Esq.';
    my $id = 'ae2640cc-234a-4dd9-95cc-3106258445b9';
    my $href = "$abookid/$id.vcf";

    my $res = $jmap->CallMethods([
        ['ContactCard/set', {
            create => {
                "1" => {
                    '@type' => 'Card',
                    version => '1.0',
                    addressBookId => $abookid,
                    uid => $id,
                    prodId => $prodid,
                    kind => 'individual',
                    created => $created,
                    name => { full => $name }
                }
            }
        }, 'R1']
    ]);

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

    $res = $carddav->Request('GET', $href, '',
                             'Accept' => 'text/vcard; version=4.0');

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

    $name =~ s/,/\\\\,/gs;       # escape commas

    $created = $now->strftime('%Y%m%dT%H%M%SZ'); # vCard doesn't use separators

    $self->assert_matches(qr/VERSION:4.0/, $card);
    $self->assert_matches(qr/KIND:INDIVIDUAL/, $card);
    $self->assert_matches(qr/UID:$id/, $card);
    $self->assert_matches(qr/PRODID:$prodid/, $card);
    $self->assert_matches(qr/CREATED:$created/, $card);
    $self->assert_matches(qr/FN:$name/, $card);
    $self->assert_does_not_match(qr|JSPROP|, $card);
}
