#!perl
use Cassandane::Tiny;

sub test_summary_with_embedded_newlines
    :MagicPlus :NoAltNameSpace
{
    my ($self) = @_;

    my $CalDAV = $self->{caldav};

    my $CalendarId = $CalDAV->NewCalendar({name => 'foo'});
    $self->assert_not_null($CalendarId);

    my $uuid = "574E2CD0-2D2A-4554-8B63-C7504481D3A9";
    my $href = "$CalendarId/$uuid.ics";
    my $card = <<EOF;
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Apple Inc.//Mac OS X 10.10.4//EN
CALSCALE:GREGORIAN
BEGIN:VEVENT
CREATED:20150806T234327Z
UID:574E2CD0-2D2A-4554-8B63-C7504481D3A9
DTEND:20160831T183000Z
TRANSP:OPAQUE
SUMMARY:Send image for 61st anniversary exhibition at gallery -- Include
 your name\, the title and the media.  To be of appropriate quality\, the
 ideal image file size should be 300 - 500 kilobytes.\\n\\nUse your last
 name and an abbreviated title as the file name
 (Lastname_Title.jpg).\\n\\nPlease send to:   foo\@example.net\\n\\n
DTSTART:20160831T153000Z
DTSTAMP:20150806T234327Z
SEQUENCE:0
END:VEVENT
END:VCALENDAR
EOF

    my %Headers = (
      'Content-Type' => 'text/calendar',
      'Authorization' => $CalDAV->auth_header(),
    );

    xlog "Create event";
    my $Response = $CalDAV->{ua}->request('PUT', $CalDAV->request_url($href), {
      content => $card,
      headers => \%Headers,
    });

    # This only succeeds if we properly encode the SUMMARY
    # as a Subject header field when constructing the message on disk
    $self->assert_num_equals(201, $Response->{status});

    xlog $self, "Check that the event made it to calendar";
    my $events = $CalDAV->GetEvents($CalendarId);
    $self->assert_equals(1, scalar @$events);

    xlog "Check Subject header";
    my $subject = "=?UTF-8?Q?Send_image_for_61st_anniversary_exhibition_at_gallery_--_Inclu?=\r\n";
    $subject .= " =?UTF-8?Q?deyour_name,_the_title_and_the_media.__To_be_of_appropriate_q?=\r\n";
    $subject .= " =?UTF-8?Q?uality,_theideal_image_file_size_should_be_300_-_500_kilobyte?=\r\n";
    $subject .= " =?UTF-8?Q?s.=0A=0AUse_your_lastname_and_an_abbreviated_title_as_the_fil?=\r\n";
    $subject .= " =?UTF-8?Q?e_name(Lastname=5FTitle.jpg).=0A=0APlease_send_to:___foo\@exam?=\r\n";
    $subject .= " =?UTF-8?Q?ple.net=0A=0A?=";

    my $store = $self->{instance}->get_service('imap')->create_store(username => 'cassandane+dav');
    my $imaptalk = $store->get_client();
    $imaptalk->select("INBOX.#calendars.$CalendarId");
    $Response = $imaptalk->fetch(1, '(BODY.PEEK[HEADER.FIELDS (SUBJECT)])');
    $self->assert_str_equals($Response->{1}->{headers}->{subject}[0], $subject);
}
