#------------------------------------------------------------
# Copyright (C) 2006 RoyaltyShare, Inc.   All Rights Reserved
# $Id$
#------------------------------------------------------------
package RPS::DB::Item::Service;

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

use base 'Common::DB::Item';

use constant kTable => 'service';
use constant kDB    => Common::DB::Item::kClientDB();

sub GetAll {
    my ($class) = @_;

    my $sql = 'SELECT * FROM ' . kTable . ' ORDER BY service_name';
    return $class->SUPER::GetAll($sql);
}

sub GetAllInPeriodSortedByName {
    my ( $class, $periodID ) = @_;
    assert( defined($periodID), "ERROR - periodID $periodID is required" );

    my $sql =
        "SELECT DISTINCT(service_name),service.service_id FROM "
      . kTable
      . " JOIN file ON file.service_id = service.service_id WHERE file_status = 4 and period_id = "
      . $periodID
      . " ORDER BY service_name";

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

sub GetAllFileServices {
    my ($class) = @_;

    my $sql =
        'SELECT '
      . kTable
      . '.* FROM service RIGHT JOIN file USING (service_id) WHERE service_id != 0 '
      . 'GROUP BY file.service_id ORDER BY service_name';
    return $class->SUPER::GetAll($sql);
}

sub GetAllServicesNeedCurrencyConversion {
    my $class = shift;

    $periodID = $class->quote($periodID);

    my $sql = qq/
        SELECT DISTINCT
            s.service_id,
            s.service_name
        FROM service AS s
        INNER JOIN file AS f ON s.service_id = f.service_id
        WHERE f.period_id = 0
            AND f.file_status = 4
            AND f.input_conversion_rate != 0
            AND f.parent_file_id IS NULL
        ORDER BY s.service_name
    /;

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

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

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

    my $where;

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

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

    $sql .= ' ORDER BY service_name';

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

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

1;
