package Searchlog;


sub new {
    my $pkg = shift;
    my $obj = {};
    bless $obj, $pkg;
    return $obj;
}


sub compile_entry  {
    my $obj = shift;
    my $IN  = { DB      => "",
                TOPIC   => "",
                FORUM   => "",
                POST    => "",
                @_,
              };
   
    my $db    = $IN->{'DB'};
    my $forum = $IN->{'FORUM'};
    my $topic = $IN->{'TOPIC'};
    my $post  = $IN->{'POST'};

    return unless length($post->{'POST'}) > 8;
    $post->{'POST'} = $obj->Convert_for_index($post->{'POST'});
    my $data = { AUTHOR_ID    => lc($topic->{'TOPIC_LAST_POSTER'}),
                 MEMBER_NAME  => $topic->{'TOPIC_LASTP_N'},
                 DATE         => $post->{'POST_DATE'},
                 TOPIC_TITLE  => lc($topic->{'TOPIC_TITLE'}),
                 POST         => $post->{'POST'},
                 FORUM_ID     => $forum->{'FORUM_ID'},
                 TOPIC_ID     => $topic->{'TOPIC_ID'},
                 POST_ID      => $post->{'POST_ID'},
                 POSTER_IP    => $post->{'IP_ADDR'},
               };
    $obj->add_entry($db, $data);
}




sub Convert_for_index {
   my ($obj, $Txt) = @_;
   $Txt =~ s!<(.+?)>!!sg;
   $Txt =~ s!\b($iB::INFO->{'SKIP_WORDS'})\b!!ig;
   # Remove punctuation
   $Txt =~ s!(\.|,|\!|\)|\(|\[|\])! !g;
   $Txt =~ s!  ! !g;
   $Txt =~ s!&.+?;!!g;
   $Txt = substr($Txt, 0, $iB::INFO->{'MAX_CHARS'}) unless $iB::INFO->{'MAX_CHARS'} eq 'ALL' or $iB::INFO->{'MAX_CHARS'} eq '';
   return lc($Txt);
}


sub remove_entry ($$) {
   my ($obj, $db, $data) = @_;
   my $post_to_remove = $db->query( TABLE   => 'search_log',
                                    ID      => $data->{'FORUM_ID'},
                                    WHERE   => "FORUM_ID == $data->{'FORUM_ID'} && TOPIC_ID == $data->{'TOPIC_ID'} && POST_ID == $data->{'POST_ID'}",
                                    MATCH   => "ONCE",
                                    COLUMNS => ['LOG_ID'],
                                  );

   $db->delete( TABLE   => 'search_log',
                ID      => $data->{'FORUM_ID'},
                KEY     => $post_to_remove->{'LOG_ID'},
              );

}




sub add_entry ($$) {
    my ($obj, $db, $data) = @_;
    $db->insert( TABLE   => 'search_log',
                 ID      => $data->{'FORUM_ID'},
                 VALUES  => $data
                );
}



1;
