# Copyright (C) 2005 FishGrove Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# $Id: NewsAggregator.pm,v 1.18 2006/03/07 14:39:10 slash5234 Exp $

package Affelio::Managing::NewsAggregator;
{
    use strict;
    use lib("../../../extlib");    
    use Error qw(:try);
    use Jcode;
    use lib("../../");
    use Affelio::misc::CGIError;
    use Affelio::misc::Time qw(get_timestamp);
    use Affelio::misc::Encoding qw(db_encode db_decode);
    use Affelio::misc::Debug qw(debug_print);
    use Affelio::misc::WSSE;
    use Affelio::exception::NetworkException;
    use Affelio::exception::CommunicationException;

    #######################################################################
    #Constructor
    #######################################################################
    sub new{
	my $class = shift;
	my $af = shift;

	debug_print("NewsAggregator::new: start.");

	my $self = {af => $af
		    };

	bless $self, $class;

	debug_print("NewsAggregator::new: end.");
	return $self;
    }

    #######################################################################
    #post_news
    #######################################################################
    sub post_news{
	my $self = shift;
	my $af = $self->{af}; 

	my %arg = @_;

	##############################
	#Insert a new record
	my $sth = "insert into $af->{site__dbtbl_prefix}_CORE_nghr_news(datetime, af_id, nickname, app_install_name, title, description, creator, URL) values ('$arg{datetime}', '$arg{af_id}', '$arg{nickname}', '$arg{app}', '$arg{title}', '$arg{desc}', '$arg{creator}', '$arg{URL}')";
	eval{
	    $sth = $af->getDB->prepare($sth);
	    $sth->execute;
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB->errstr);
	}
	undef($sth);
    }

    #######################################################################
    #retrieve_news
    #######################################################################
    sub retrieve_news{
	my $self = shift;
	my $af = $self->{af}; 
	my $num = shift;

	debug_print("NewsAggregator::retrieve_news: start.");

	##############################
	#retrieve all friend records from DB
	my $query = "SELECT datetime, af_id, nickname, app_install_name, title, description, creator, URL FROM $af->{site__dbtbl_prefix}_CORE_nghr_news order by datetime desc";
	my $sth;
	eval{
	    $sth = $af->getDB->prepare($query);
	    $sth->execute();
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB->errstr);
	}
	
	debug_print("NewsAggregator::retrieve_news: end.");
	return($sth);
    }


    #######################################################################
    #get_one
    #######################################################################
    sub get_one{
	my $self = shift;
	my $af = $self->{af}; 

	debug_print("NewsAggregator::get_one: start.");

	#########################################################
	#Get a friend whose last_news_in is smallet (oldest).
	my $threshold = Affelio::misc::Time::get_timestamp() - 1000; #-10m
	my $result = $af->getFM->get_all_friend_list(
                     where => "last_news_in  < $threshold",  
		     sort => "last_incoming",
  	             order => "desc");
	debug_print("NewsAggregator::get_one: FM access done.");

	my @row = $result->fetchrow_array;
	if(!@row){ return; }

	#uid, af_id, nickname, timestamp, password, intro, option_pid, lastupdated, f2list, last_news_in, last_news_out
	my $uid = $row[0];
	my $af_id = $row[1];
	my $nickname = $row[2];
	my $password = $row[4];
	debug_print("NewsAggregator::get_one: [$uid, $af_id, $nickname, $password]");

	#########################################################
	#generate X-WSSE message
	my $xwsse_mesg = Affelio::misc::WSSE::make_XWSSE($af->{site__user_afid},
							 $password);
	debug_print("NewsAggregator::get_one: [$xwsse_mesg]");

	#########################################################
	#update AFuser_CORE_friends
	my $curtime = Affelio::misc::Time::get_timestamp();
	my $result = $af->getFM->set_attribute_by_id($uid,
						     "last_news_in",
						     $curtime);
	debug_print("NewsAggregator::get_one: updated_last_news_in");

	#########################################################
	#Invoke SNS/Handshaker_c
	my $ret="";
	try{
	    require Affelio::SNS::Handshaker_c;

	    $ret = Affelio::SNS::Handshaker_c::get_news(
                   dest_uri =>  $af_id,
		xwsse_mesg => $xwsse_mesg);

	}catch Error with{
	    my $e = shift;
	    debug_print("NewsAggregator::get_one: ERR[$e]");
	    return;
	};

	if( (!defined($ret)) 
	    || ($ret eq "") 
	    || !(defined($ret->{flerror}))
	    || ($ret->{flerror} != 0 )
	    || !(defined($ret->{message}))
	    ){
	    debug_print("NewsAggregator::get_one: XML-RPC error.");
	    return;
	}
	if($ret->{message} eq ""){
	    debug_print("NewsAggregator::get_one: No News.");
	    return;
	}

	#########################################################
	#Analyze returned value
	debug_print("NewsAggregator::get_one: ret=[$ret]");

	#########################################################
	#Post data into NeighborNews table
	my @elements = split('\n', $ret->{message});
	my $size = @elements;
	my $index=0;
	while($index < $size){
	    my $datetime = $elements[$index++];
	    my $app_install_name = $elements[$index++];
	    my $title = $elements[$index++];
	    my $desc = $elements[$index++];
	    my $creator = $elements[$index++];
	    my $URL = $elements[$index++];

	    debug_print("NewsAggregator::get_one: date = $datetime");
	    debug_print("NewsAggregator::get_one: afid = $af_id");
	    debug_print("NewsAggregator::get_one: app = $app_install_name");
	    debug_print("NewsAggregator::get_one: title= $title");
	    debug_print("NewsAggregator::get_one: desc= $desc");
	    debug_print("NewsAggregator::get_one: creator= $creator");
	    debug_print("NewsAggregator::get_one: URL = $URL");

	    post_news($self,
		      datetime => $datetime,
		      af_id => $af_id,
		      nickname => $nickname,
		      app => $app_install_name,
		      title => $title,
		      desc => $desc,
		      creator => $creator,
		      URL => $URL);
	}


	#########################################################
	#update AFuser_CORE_friends
	my $curtime = Affelio::misc::Time::get_timestamp();
	my $result = $af->getFM->set_attribute_by_id($uid,
						     "last_news_in",
						     $curtime);
    }



    #######################################################################
    #show
    #######################################################################

}#package
1;
