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

package Affelio::Managing::AccessLogManager;
{
    use strict;
    use lib("../../../extlib");    
    use DBI;
    use Jcode;
    use lib("../../");
    use Affelio::misc::CGIError;
    use Affelio::misc::Time qw(get_timestamp get_today);
    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("AccessLogManager::new: start.");

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

	bless $self, $class;

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

    #######################################################################
    #save_log
    #######################################################################
    sub save_log{
	my $self=shift;
	my $afid = shift;
	my $nickname = shift;
	my $type=shift;

	#AFuser_CORE_accesslog
	# id id2 timestamp INT, nickname TEXT, afid TEXT, type TEXT

	my $af=$self->{af};
	my $cur_time = get_timestamp();
	my $startoftheday = get_today();

	################################
	#Check the table
	################################
	my $create_tbl_cmd = "CREATE TABLE $af->{site__dbtbl_prefix}_CORE_accesslog(id INTEGER PRIMARY KEY, id2 INTEGER, timestamp BIGINT, nickname TEXT, afid TEXT, type TEXT)";
	eval{
	    $af->getDB()->do($create_tbl_cmd);
	};
	if($@){
	}else{
	    debug_print("AccessLog:save: Table created.");
	}

	################################
	#check today's past access of this user
	################################
	my $query1; my $sth1; 	$@="";
	my @row1=();
	$query1 = "SELECT * FROM $af->{site__dbtbl_prefix}_CORE_accesslog WHERE timestamp >= $startoftheday AND afid = '$afid'";
	debug_print("AccessLog:save: q=[$query1]");
	eval{
	    $sth1 = $af->getDB()->prepare($query1);
	    $sth1->execute();
	    @row1 = $sth1->fetchrow_array;
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB()->errstr);
	}

	if(@row1 == () ){
	    debug_print("AccessLog:save: This is your 1st access today. proceed.");
	    my $newid=0; my $maxid=0;

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

	    my @row2 = $sth2->fetchrow_array;
	    $maxid = $row2[0];
	    debug_print("AccessLog:save: maxid=[$maxid]");

	    if(defined($row2[0])){
		$maxid = $row2[0];
	    }else{
		$maxid = 0;
	    }
	    $newid = $maxid+1;

	    ##############################
	    #Get existing max ID2
	    my $newid2=0; my $maxid2=0;
	    if($afid =~ /http/){
		$query2 = "SELECT max(id2) FROM $af->{site__dbtbl_prefix}_CORE_accesslog";
		eval{
		    $sth2 = $af->getDB()->prepare($query2);
		    $sth2->execute;
		};
		if($@){
		    throw Affelio::exception::DBException($af->getDB()->errstr);
		}

		@row2 = $sth2->fetchrow_array;
		$maxid2 = $row2[0];
		debug_print("AccessLog:save: maxid2=[$maxid2]");
		if(defined($row2[0])){
		    $maxid2 = $row2[0];
		}else{
		    $maxid2 = 0;
		}
		$newid2 = $maxid2+1;
	    }

	    ################################
	    #Add this access
	    ################################
	    my $query3; my $sth3;
	    $query3 = "insert into $af->{site__dbtbl_prefix}_CORE_accesslog(id, id2, timestamp, nickname, afid, type) values ($newid, $newid2, $cur_time, '$nickname', '$afid', '$type')";
	    eval{
		$sth3 = $af->getDB()->prepare($query3);
		$sth3->execute();
	    };
	    debug_print("AccessLog:save: inserted [$query3]");
	    if($@){
		throw Affelio::exception::DBException($af->getDB()->errstr);
	    }

	    debug_print("AccessLog:save: recorded!");
	}else{
	    debug_print("AccessLog:save: You are a repeater. ignore you.");
	}

	if($type eq "f1"){
	    eval{
		$af->getFM->set_attribute_by_afid($afid,
						  "last_access",
				  Affelio::misc::Time::get_timestamp()
					  );

		$af->getFM->incr_attribute_by_afid($afid,
						   "count_access");

	    };
	    if($@){
		throw Affelio::exception::DBException($af->getDB()->errstr);
	    };
	}

    }

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

	my %param = @_;

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

	my $from = $param{t_begin};
	my $to = $param{t_end};
	my $type = $param{view};

	debug_print("AccessLog::get_log: $from -> $to  [$type]");

	################################
	#Check the table
	################################
	my $create_tbl_cmd = "CREATE TABLE $af->{site__dbtbl_prefix}_CORE_accesslog(id INTEGER PRIMARY KEY, id2 INTEGER, timestamp INTEGER, nickname TEXT, afid TEXT, type TEXT)";
	eval{
	    $af->getDB()->do($create_tbl_cmd);
	};
	if($@){
	}else{
	    debug_print("AccessLog:save: Table created.");
	}


	my $TYPE="";
	if($type eq "affelio"){
	    $TYPE=" and type != 'pb' ";
	}elsif(($type eq "f1") || ($type eq "f2") || ($type eq "pb")){
	    $TYPE=" and type = '$type' ";
	}

	##############################
	#retrieve all friend records from DB
	my $query = "SELECT * FROM $af->{site__dbtbl_prefix}_CORE_accesslog WHERE timestamp > $from AND timestamp < $to " . $TYPE . " order by id desc";
	my $sth;
	eval{
	    $sth = $af->getDB()->prepare($query); 
	    $sth->execute;
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB()->errstr);
	}
	return($sth);
    }

}#package
1;


