#!perl
use Cassandane::Tiny;

sub test_email_set_encode_plain_text_attachment
    :needs_component_sieve :needs_dependency_chardet
{
    my ($self) = @_;

    my $jmap = $self->{jmap};

    my $text = "This line ends with a LF\nThis line does as well\n";

    my $data = $jmap->Upload($text, "text/plain");
    my $blobId = $data->{blobId};

    my $email = {
        mailboxIds => { '$inbox' => JSON::true },
        from => [{ name => "Test", email => q{test@local} }],
        subject => "test",
        bodyStructure => {
            type => "multipart/mixed",
            subParts => [{
                type => 'text/plain',
                partId => '1',
            }, {
                type => 'text/plain',
                blobId => $blobId,
            }, {
                type => 'text/plain',
                disposition => 'attachment',
                blobId => $blobId,
            }]
        },
        bodyValues => {
            1 => {
                value => "A plain text body",
            }
        }
    };
    my $res = $jmap->CallMethods([
        ['Email/set', { create => { '1' => $email } }, 'R1'],
        ['Email/get', {
            ids => [ '#1' ],
            properties => [ 'bodyStructure', 'bodyValues' ],
            bodyProperties => [
                'partId', 'blobId', 'type', 'header:Content-Transfer-Encoding', 'size'
            ],
            fetchAllBodyValues => JSON::true,
        }, 'R2' ],
    ]);

    xlog $self, "Assert that bare LF in inlined plain text gets expanded to CR LF";
    my $subPart = $res->[1][1]{list}[0]{bodyStructure}{subParts}[1];
    $self->assert_str_equals(' 7bit', $subPart->{'header:Content-Transfer-Encoding'});
    my $subPartBlob = $jmap->Download('cassandane', $subPart->{blobId});
    $self->assert_str_equals("This line ends with a LF\r\nThis line does as well\r\n",
        $subPartBlob->{content});

    xlog $self, "Assert that bare LF in attached plain text is kept as-is";
    $subPart = $res->[1][1]{list}[0]{bodyStructure}{subParts}[2];
    $self->assert_str_equals(' base64', $subPart->{'header:Content-Transfer-Encoding'});
    $subPartBlob = $jmap->Download('cassandane', $subPart->{blobId});
    $self->assert_str_equals("This line ends with a LF\nThis line does as well\n",
        $subPartBlob->{content});
}
