%# Shaw's Principle:
%#     Build a system that even a fool can use, and only a fool will
%#     want to use it.

<%PERL>

my %col_ok = map {
    $_ => 1, "$_-Boolean" => 1, "$_-Boolean-Magic" => 1
} @$AddMoreEntry;

if ($TicketObj) {
    my $CustomFields = $TicketObj->QueueObj->CustomFields();
    while (my $CustomField = $CustomFields->Next()) {
	next unless ($CustomField->IsEntry);
	$Entries->{$CustomField->Id} = [ map {
	    $_->Content
	} @{$TicketObj->CustomFieldValues($CustomField->Id)->ItemsArrayRef} ];
    }
}

# {{{ deal with entries

# update
my $added_entry;
foreach my $key (reverse sort keys %ARGS) {
    if ($key =~ m/^Entry-((\d+).*)$/ and (!%col_ok or $col_ok{$2})) {
	my $col = $1;
	my $values = $ARGS{$key};

	$values = [ $values ] unless ref $values;

	if ($col =~ s/-Boolean$//) {
	    # this is a boolean field.
	    @$values = map { ($_ eq 'off') ? 0 : 1 } @$values;
	}
	elsif ($col =~ s/-Boolean-Magic$//) {
	    @$values = (0) x @$values;
	}

	$Entries->{$col}[$_] = $values->[$_] for (0 .. $#{$values});
    }
}

# delete and insert
my @deleted_entry;
foreach my $key (sort keys %ARGS) {
    if ($key =~ m/^DeleteEntry-(.+)$/) {
	# $1 is row, not column here!
        push @deleted_entry, $1;
    }
    if ($key =~ m/^AddEntry-(.+)$/ and (!%col_ok or $col_ok{$1})) {
	my $value = $ARGS{$key};
	my $k = $1;
	if ($k =~ s/-Boolean//) {
	    $value = (!$value or $value eq 'off') ? '0' : '1';
	}
	$added_entry->{$k} = $value;
    }
}

foreach my $row (reverse sort @deleted_entry) {
    foreach my $col (keys %col_ok) {
        next unless exists $Entries->{$col};
        splice(@{$Entries->{$col}}, $1, 1);
    }
}

# }}}

# {{{ now add back the new entries, if at least one value is given
my $LastIndex = -1;
delete $col_ok{$_} foreach grep /-Boolean/, keys %col_ok;
my @keys = keys %col_ok;
@keys = keys %$Entries if !%col_ok;
foreach my $col (@keys) {
    $LastIndex = $#{$Entries->{$col}}
	if $#{$Entries->{$col}} > $LastIndex;
}

if (
    grep {
	length($added_entry->{$_})
	and !/-Magic$/
	and !$ARGS{"ReadOnly-Entry-$_"}
	and !$ARGS{"ReadOnly-AddEntry-$_"}
    } keys %$added_entry
    and !grep $m->notes("InvalidField-$_"), keys %$added_entry
) {
    $LastIndex++;

    while (my ($col, $value) = each %$added_entry) {
	$Entries->{$col}[$LastIndex] = (length($value) ? $value : ' ');
    }
}

# }}}

return $Entries;

</%PERL>
<%ARGS>
$Entries    => {}
$TicketObj  => undef
$AddMoreEntry => []
</%ARGS>
