#!/usr/bin/env perl
require 5.008;
use warnings;
use strict;

unshift(@INC, '.');
require qpdf_test_helpers;

chdir("qpdf") or die "chdir testdir failed: $!\n";

require TestDriver;

cleanup();

my $td = new TestDriver('appearance-streams');

my $n_tests = 12;

foreach my $f ('need-appearances',
               'need-appearances-more',
               'need-appearances-more2',
               'need-appearances-more3')
{
    $td->runtest("generate appearances and flatten ($f)",
                 {$td->COMMAND =>
                      "qpdf --qdf --no-original-object-ids --static-id" .
                      " --generate-appearances --flatten-annotations=all" .
                      " $f.pdf a.pdf"},
                 {$td->STRING => "", $td->EXIT_STATUS => 0},
                 $td->NORMALIZE_NEWLINES);
    my $exp = 'appearances-a';
    if ($f =~ m/appearances(-.*)$/)
    {
        $exp .= $1;
    }
    $exp .= '.pdf';
    $td->runtest("compare files",
                 {$td->FILE => "a.pdf"},
                 {$td->FILE => $exp});
}

$td->runtest("more choices",
             {$td->COMMAND =>
                  "qpdf --qdf --no-original-object-ids --static-id" .
                  " --generate-appearances" .
                  " more-choices.pdf b.pdf"},
             {$td->STRING => "", $td->EXIT_STATUS => 0},
             $td->NORMALIZE_NEWLINES);
# b.pdf still has forms
$td->runtest("compare files",
             {$td->FILE => "b.pdf"},
             {$td->FILE => "appearances-b.pdf"});

my @choice_values = qw(1 2 11 12 quack);
$n_tests += 3 * scalar(@choice_values);
foreach my $i (@choice_values)
{
    # b.pdf was generated by qpdf and needs appearances
    # test_driver 52 writes a.pdf
    $td->runtest("set value to $i",
                 {$td->COMMAND => "test_driver 52 b.pdf $i"},
                 {$td->STRING => "setting list1 value\ntest 52 done\n",
                      $td->EXIT_STATUS => 0},
                 $td->NORMALIZE_NEWLINES);
    $td->runtest("regenerate appearances",
                 {$td->COMMAND =>
                      "qpdf --qdf --no-original-object-ids --static-id" .
                      " --generate-appearances" .
                      " a.pdf b.pdf"},
                 {$td->STRING => "", $td->EXIT_STATUS => 0},
                 $td->NORMALIZE_NEWLINES);
    $td->runtest("compare files",
                 {$td->FILE => "b.pdf"},
                 {$td->FILE => "appearances-$i.pdf"});
}

$td->runtest("Update resources from /DR",
             {$td->COMMAND =>
                      "qpdf --qdf --no-original-object-ids --static-id" .
                      " --generate-appearances" .
                      " resource-from-dr.pdf a.pdf"},
             {$td->STRING => "", $td->EXIT_STATUS => 0},
             $td->NORMALIZE_NEWLINES);
$td->runtest("compare files",
             {$td->FILE => "a.pdf"},
             {$td->FILE => "resource-from-dr-out.pdf"});

cleanup();
$td->report($n_tests);
