# 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: MessageManager.pm,v 1.14 2006/03/07 14:39:10 slash5234 Exp $

package Affelio::Managing::MessageManager;
{
    use strict;
    use lib("../../../extlib");    
    use DBI;
    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::NetLib::Email qw(send_email);
    use Affelio::exception::DBException;

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

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

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

	bless $self, $class;

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

    #MessageManager looks up each application directory
    #to get the whole list of message types.

    ########################################################################
    #get_unread_message_num
    ########################################################################
    sub get_unread_message_num{
	my $self = shift;

	debug_print("MM::get_unread_message_num: start");
	my $af = $self->{af};

	my $sth;
	eval{
	    $sth = $af->getDB->prepare("SELECT * FROM $af->{site__dbtbl_prefix}_CORE_message where readflag=0");
	    $sth->execute;
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB->errstr);
	    return("");
	}

	my $count=0;
	while(my @row = $sth->fetchrow_array){
	    $count++;
	}

	debug_print("MM::get_unread_message_num: end");
	return($count);
    }


    ########################################################################
    #mark_as_read
    ########################################################################
    sub mark_as_read{
	my $self = shift;
	my $mid  =shift;

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

	my $query = "update $af->{site__dbtbl_prefix}_CORE_message set readflag = 1 where mid = $mid";
	my $sth;
	eval{
	    $sth = $af->getDB->prepare($query);
	    $sth->execute;
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB->errstr);
	}

	debug_print("MM::retrieve_all: end");
	return();
    }


    ########################################################################
    #retrieve_all_messages
    ########################################################################
    #sub SQL_result get_all_group_list
    #  result (mid,timestamp,msg_title,msg_type,msg_from,msg_body,readflag)
    sub retrieve_all_messages{
	my $self = shift;

	debug_print("MM::retrieve_all: start");
	my $af = $self->{af};

	##############################
	#retrieve all friend records from DB
	my $sth;
	eval{
	    $sth = $af->getDB->prepare("SELECT * FROM $af->{site__dbtbl_prefix}_CORE_message order by timestamp desc");
	    $sth->execute;
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB->errstr);
	}

	debug_print("MM::retrieve_all: end");
	return($sth);
    }

    ########################################################################
    #retrieve_message
    ########################################################################
    #sub SQL_result get_all_group_list
    #  result (mid,timestamp,msg_title,msg_type,msg_from,msg_body,readflag)
    sub retrieve_message{
	my $self = shift;
	my $mid = shift;

	debug_print("MM::retrieve: start");
	my $af = $self->{af};

	##############################
	#retrieve all friend records from DB
	my $sth;
	eval{
	    $sth = $af->getDB->prepare("SELECT * FROM $af->{site__dbtbl_prefix}_CORE_message where mid = $mid");
	    $sth->execute;
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB->errstr);
	}

	my @row = $sth->fetchrow_array;

	if(!@row){
	    debug_print("MM::retrieve Error: No such group.");
	    return;
	}

	debug_print("MM::retrieve: end");
	return(@row);
    }

    #######################################################################
    #post_message 
    #  arg1 SenderName:   (app_name)
    #  arg2 Title: (UTF-8)
    #  arg3 Type: (Ascii)
    #  arg4 Body: (free text including URL)
    #######################################################################
    sub post_message{
	my $self = shift;
	my $from = shift;    #1
	my $title = shift;   #2
	my $type = shift;    #3
	my $body = shift;    #4

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

	Affelio::misc::Debug::debug_print("MM::post_message: start.");

	##############################
	#Get existing max ID
	my $sth;
	eval{
	    $sth = $af->getDB->prepare("SELECT max(mid) FROM $af->{site__dbtbl_prefix}_CORE_message");
	    $sth->execute;
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB->errstr);
	}

	my @row = $sth->fetchrow_array;
	my $maxid = $row[0];
	if(defined($row[0])){
	    $maxid = $row[0];
	}else{
	    $maxid = 0;
	}
	my $newid = $maxid+1;
	Affelio::misc::Debug::debug_print("MM::post_message: newid = $newid");

	my $cur_time = Affelio::misc::Time::get_timestamp();

	Affelio::misc::Debug::debug_print("MM::post_message: Writing to DB...");
	Affelio::misc::Debug::debug_print("MM::post_message: [$body]");

	Affelio::misc::Debug::debug_print("size [" . length($body) ."]");

	##############################
	#Insert a new record
	my $str10 = "insert into $af->{site__dbtbl_prefix}_CORE_message(msgbody, mid, timestamp, msgtitle, msgtype, msgfrom, readflag) values ('$body', $newid, '$cur_time', '$title', '$type', '$from', 0)";
	eval{
	    $sth = $af->getDB->prepare($str10);
	    $sth->execute;
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB->errstr);
	}
	undef($sth);


	my $from_onlyname = $from;
	$from_onlyname =~ s|<A HREF=".*">(.*)</A>|$1|;

	##############################
	#Email notification if needed
	if($af->{userpref__mesging__emailflg} eq "yes"){
	    my $abs_URL = $af->{site__user_afid} . "/admin.cgi?mode=messages&action=show&mid=$newid";
	    Affelio::NetLib::Email::send_email($af->{cmd__sendmail}, "$af->{user__email1}", "Your Affelio", $af->{user__email1}, "Message from $from_onlyname", "Click this URL.\n$abs_URL");

	    Affelio::misc::Debug::debug_print("MM::post_message: Email sent!");
	}

	Affelio::misc::Debug::debug_print("MM::post_message: end.");
	return("");
    }

}#package
1;
