package Common::DB::Item::News;

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 => 'news';
use constant kDB    => Common::DB::Item::kCommonDB;

use constant kNewsDaysToExpire   => 7;
use constant kDaysArticleCurrent => 3;

sub GetAll {
    my $class = shift;

    return $class->SUPER::GetAll( "SELECT * FROM " . kTable . " ORDER BY date_published DESC" );
}

sub DeleteExpired {
    my $class = shift;
    my $dbo   = Common::RSApp::GetCommonDB;

    my $sql = "DELETE FROM " . kTable . " WHERE date_published < DATE_SUB( now(), interval " . kNewsDaysToExpire . " day )";
    $dbo->DoCmd($sql);
}

sub FreshArticles {
    my $class = shift;
    my $dbo   = Common::RSApp::GetCommonDB;

    my $sql = "SELECT * FROM " . kTable . " WHERE date_published >= DATE_SUB( now(), interval " . kDaysArticleCurrent . " day )";
    $class->SUPER::GetAll($sql);
}

sub LookupByURL {
    my $class = shift;
    my $url   = shift;
    my $dbo   = Common::RSApp::GetCommonDB;

    my $sql = "SELECT * FROM " . kTable . " WHERE url =" . $dbo->DBQuote($url);

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

sub GetLatest {
    my $class = shift;
    my %args  = @_;
    my $limit = $args{limit};

    my $sql = "SELECT * FROM " . kTable . " WHERE approved = 1 " . " ORDER BY date_published DESC ";

    # Use this order by if we want to randomize articles returned, they still
    # will be prioritized by day.
    #              " ORDER BY DATE(date_published), RAND() ";

    $sql .= " LIMIT $limit";

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

1;
