#!perl
use Cassandane::Tiny;

sub test_sieve_test_singlecommand
    :min_version_3_3 :JMAPExtensions
{
    my ($self) = @_;

    my $email1 = <<'EOF';
From: "Some Example Sender" <example@example.com>
To: cassandane@example.com
Subject: test email
Date: Wed, 7 Dec 2016 22:11:11 +1100
MIME-Version: 1.0
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable

This is a test email.
EOF
    $email1 =~ s/\r?\n/\r\n/gs;

    my $email2 = <<'EOF';
From: "Some Example Sender" <example@example.com>
To: cassandane@example.com
Subject: Hello!
Date: Wed, 7 Dec 2016 22:11:11 +1100
MIME-Version: 1.0
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable

This is a test email.
EOF
    $email2 =~ s/\r?\n/\r\n/gs;

    my $script = <<EOF;
require ["fileinto", "imap4flags", "copy", "variables", "mailbox", "mailboxid", "special-use", "vacation"];
if header :contains "subject" "test" {
  setflag "\\Seen\";
  fileinto :copy :flags ["\\Flagged", "\\Answered"] :specialuse "\\Flagged" :create "INBOX.foo";
}
else {
  vacation "Gone fishin'";
}
EOF
    $script =~ s/\r?\n/\r\n/gs;
    $script =~ s/\\/\\\\/gs;

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

    xlog "test script";
    my $res = $jmap->CallMethods([
        ['Blob/upload', {
            create => {
                "1" => { data => [{'data:asText' => $email1}] },
                "3" => { data => [{'data:asText' => $email2}] },
                "2" => { data => [{'data:asText' => $script}] },
            }}, 'R0'],
        ['SieveScript/test', {
            emailBlobIds => [ '#1', 'foobar', '#3' ],
            scriptBlobId => '#2',
            envelope => {
                mailFrom => {
                    email => 'foo@example.com',
                    parameters => JSON::null
                },
                rcptTo => [ {
                    email => 'cassandane@example.com',
                    parameters => JSON::null
                } ]
            },
            lastVacationResponse => JSON::null
         }, "R1"]
    ]);
    $self->assert_not_null($res);

    my $emailid1 = $res->[0][1]{created}{1}{blobId};
    my $emailid2 = $res->[0][1]{created}{3}{blobId};

    $self->assert_not_null($res->[1][1]{completed});
    $self->assert_str_equals('fileinto',
                             $res->[1][1]{completed}{$emailid1}[0][0]);
    $self->assert_str_equals('keep',
                             $res->[1][1]{completed}{$emailid1}[1][0]);
    $self->assert_str_equals('vacation',
                             $res->[1][1]{completed}{$emailid2}[0][0]);
    $self->assert_str_equals('keep',
                             $res->[1][1]{completed}{$emailid2}[1][0]);

    $self->assert_not_null($res->[1][1]{notCompleted});
    $self->assert_str_equals('blobNotFound',
                             $res->[1][1]{notCompleted}{foobar}{type});
}
