#!/usr/bin/perl
#

use strict;

package Common::News::UpdateFeed;

use lib '/app/tools/common/lib';
use Common::RSApp;
use Common::Util;
use Common::Assert;
use Common::DB::Item::News;
use Common::DB::Item::Feed;

use Common::UTF8;

use lib '/app/tools/support/lib';
use Support::News::FeedList;
use Support::News::NewsList;

use base 'Common::CronScript';

use Data::Dumper;

sub _init {
    my $self = shift;
    my %args = @_;
    $self->SUPER::_init(@_);

    $self->{_product} = $args{product};

    assert( $self->{_product}, "product required" );

    return $self;
}

sub run_process {
    my $self = shift;

    my $singleton = new Common::RSApp( clientID => 0 );

    $self->_addNewsFeeds();
    $self->_deleteExpiredNews();
}

sub _deleteExpiredNews {
    my $self = shift;
    Common::DB::Item::News->DeleteExpired();
}

sub _addNewsFeeds {
    my $self = shift;
    my $feeds = Support::News::FeedList->new( product => $self->{_product} );

    my @newsAdded;

    foreach my $feed ( $feeds->Feeds() ) {
        push( @newsAdded, $self->_addNews($feed) );
    }

    if (@newsAdded) {
        Common::Log::Debug( "Added " . @newsAdded . " new article" );
        $self->_notify( \@newsAdded );
    } else {
        $self->_checkForStale();
    }
}

sub _checkForStale {
    my $self = shift;

    my $collection = Common::DB::Item::News->FreshArticles();

    unless ( $collection->hasNext() ) {
        print STDERR "No articles have been added in more than " . Common::DB::Item::News::kDaysArticleCurrent . " days\n";
    }
}

sub _notify {
    my $self = shift;
    my $articles = shift || return;

    print "***** Added the following articles for $self->{_product} news *****\n\n";

    foreach my $article (@$articles) {
        if ( $article->{Approved} ) {
            print Common::UTF8::ToAscii( $article->{Title} ) . "\n";
            print "$article->{URL}\n\n";
        }
    }

    print "\n\n*****  Rejected the following articles for $self->{_product} news *****\n\n";

    foreach my $article (@$articles) {
        unless ( $article->{Approved} ) {
            print Common::UTF8::ToAscii( $article->{Title} ) . "\n";
            print "$article->{URL}\n\n";
        }
    }

}

sub _addNews {
    my $self = shift;
    my $feed = shift || die;
    my @saved;

    my @newNews = $feed->getNews();

    if ( $feed->error ) {
        print STDERR $feed->error . "\n";
    }

    foreach my $news (@newNews) {
        if ( !$news->isDuplicate() && !$news->isExpired() ) {
            $news->addToDB();
            push( @saved, $news );
        }
    }

    return @saved;
}

1;
