package Search::OpenFTS::Dict::UnknownDict;
use strict;
use locale;

=head1 NAME 

Search::OpenFTS::Dict::UnknownDict - The dictionary of unknown words

=head1 SYNOPSIS

=head2 The designer

my $voc=Search::OpenFTS::Dict::UnknownDict->new( DBI=>$dbi, index=>[ 0 | 1 ], table=>NAME_OF_TABLE );

index - Use 1 to store and index unknown lexemes, otherwise use 0. If DBI is ommited then
dictionary doesn't store word in table and always return lowercased word.

my $voc=Search::OpenFTS::Dict::UnknownDict->init( DBI=>$dbi );

At creation of the dictionary

$voc->drop - drop table;
=cut 

sub new {
    my ( $class, %opt ) = @_;
    $class = ref($class) || $class;
    my $self = {};

    $self->{RW} = $opt{index};
    if ( ref $opt{DBI} ) {
        $self->{USE_DB} = 1;
        $self->{TABLE}  = $opt{table};
        $self->{DBI}    = $opt{DBI};
        $self->{TABLE} ||= 'fts_unknown_lexem';
    } else {
        $self->{USE_DB} = 0;
    }

    bless( $self, $class );
    return $self;
}

sub init {
    my ( $class, %opt ) = @_;
    $opt{index} = 1;
    my $self = Search::OpenFTS::Dict::UnknownDict->new(%opt);
    return if !ref $self;

    if ( $self->{USE_DB} ) {
        my $success = $self->{DBI}->do( "
			create table $self->{TABLE} (
 				lexem   varchar primary key
			);" );
        return ($success) ? $self : undef;
    }
    return $self;
}

=head2 Methods

=over 4

=item lemms( $word ) 

Returns the list of lexemes for a given word

=cut

sub lemms {
    my ( $self, $word ) = @_;
    $word = lc $word;

    return ($word) if !$self->{USE_DB};

    $self->{STH} ||=
      $self->{DBI}
      ->prepare("select count(*) from $self->{TABLE} where lexem = ? ");
    return () if !$self->{STH};
    $self->{STH}->execute($word);
    my @row = $self->{STH}->fetchrow_array;
    $self->{STH}->finish;

    return ($word) if ( $#row >= 0 && $row[0] );

    if ( $self->{RW} ) {
        $self->{INS} ||=
          $self->{DBI}
          ->prepare("insert into $self->{TABLE} (lexem) values ( ? );");
        return () if !$self->{INS};
        $self->{INS}->execute($word) || return ();
        return ($word);
    }
    return ();
}

sub drop {
    my $self = shift;

    return if !$self->{USE_DB};

    $self->{DBI}->do("drop table $self->{TABLE};")
      || warn "Can't drop table $self->{TABLE}";
}

sub fix_permissions {
    my ( $self, $user ) = @_;

    $user ||= 'PUBLIC';

    return $self->{DBI}->do("grant select on $self->{TABLE} to $user;");
}

=head1 SEE ALSO

    The OpenFTS Primer          (  see doc/ subdirectory )

    The Crash-course to OpenFTS ( in examples/ subdirectory )

    perldoc Search::OpenFTS::Search

    perldoc Search::OpenFTS::Index

    perldoc Search::OpenFTS::Parser

    perldoc Search::OpenFTS::Dict::PorterEng

    perldoc Search::OpenFTS::Dict::Snowball

    perldoc Search::OpenFTS::Morph::ISpell

=cut

1;

