package Common::DB::Item::Language;

use strict;
use warnings;

use lib '/app/tools/common/lib';
use Common::DB::ItemCollection;
use Common::DB::Item;
use base 'Common::DB::Item';

use constant kTable => 'language';
use constant kDB    => Common::DB::Item::kCommonDB;

sub Search {
    my ( $class, %args ) = @_;

    my $searchTerm = $args{searchTerm};
    my $limit      = $args{limit};

    my $where;

    if ($searchTerm) {
        $where = $class->SUPER::SearchSyntax( field => 'name', value => $searchTerm );
    }

    my $sql = 'SELECT * FROM ' . kTable;
    if ($where) {
        $sql .= " WHERE $where";
    }

    $sql .= ' ORDER BY name';

    if ($limit) {
        $sql .= " LIMIT $limit";
    }

    Common::Log::Debug("SEARCH: $sql");

    return $class->SUPER::GetAll($sql);
}

sub LanguageLookup {
    my ( $class, %args ) = @_;

    my $language;
    my $value = $args{value};

    if ( length($value) == 2 ) {

        # For now, the only code we are supporting in this method is part1.
        $language = Common::DB::Item::Language->Lookup( part1 => lc($value) );
    } else {
        my $searchResults = Common::DB::Item::Language->Search( searchTerm => $value );

        while ( $searchResults->hasNext() ) {
            my $searchResult = $searchResults->next();
            if ( lc($value) eq lc( $searchResult->name ) ) {
                $language = $searchResult;
                last;
            }
        }
    }

    return $language;
}

sub getAllLanguages {
    my $class = shift;

    my $dbo = Common::RSApp->GetCommonDB();
    my $sth = $dbo->DoCmd( 'SELECT * FROM ' . kTable );
    my $aData = $sth->fetchall_arrayref({});

    return $aData;
}

1;
