# Copyright 1999-2004, Fred Steinberg, Brown Bear Software

# Filter out Tentative Events

package TentativeFilter;
use strict;

# Pass operation and list of events
# Pass listref of events, return those that are not Tentative, or that we
# have Edit permission for
sub filter {
    my ($class, $op, $events) = @_;
    my @keepers;
    my $calName = $op->calendarName;
    $op->{_canEdit} ||= {};

    my $tentViewers = $op->prefs->TentativeViewers || 'edit';

    return @$events if (lc ($tentViewers) eq 'all');

    my $ownerView = ($tentViewers =~ /owner/i);
    my $user      = ($op->getUsername || ' anon ');
    my $editors   = ($tentViewers =~ /edit/i);
    my $admins    = ($tentViewers =~ /admin/i);

    foreach (@$events) {
        if (!$_->isTentative) {
            push @keepers, $_;
            next;
        }
        if ($ownerView and ((!$_->owner) or $_->owner eq $user)) {
            push @keepers, $_;
            next;
        }
        if ($editors) {
            my $cal = $_->includedFrom || $calName;
            if (!exists $op->{_canEdit}->{$cal}) {
                $op->{_canEdit}->{$cal} =
                        $op->permission->permitted ($op->getUsername, 'Edit');
            }
            if ($op->{_canEdit}->{$cal}) {
                push @keepers, $_;
                next;
            }
        }
        if ($admins) {
            my $cal = $_->includedFrom || $calName;
            if (!exists $op->{_canAdmin}->{$cal}) {
                $op->{_canAdmin}->{$cal} =
                        $op->permission->permitted ($op->getUsername, 'Admin');
            }
            if ($op->{_canAdmin}->{$cal}) {
                push @keepers, $_;
                next;
            }
        }
    }
    return @keepers;
}

1;
