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

package Affelio::Managing::GroupManager;
{
    use strict;

    use lib("../../../extlib");    
    use DBI;

    use lib("../../");
    use Affelio;
    use Affelio::misc::CGIError;
    use Affelio::misc::Debug qw(debug_print);
    use Affelio::misc::DBroutines qw(db_value_replace);

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

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

	my $self = {af => $af
		    };
	bless $self, $class;

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

    ########################################################################
    #add_group
    ########################################################################
    sub add_group{                  #returns gid (int)
	my $self = shift;
	my $group_name = shift;      #arg(1) group_name (string)

	debug_print("add_group: [$group_name]");
	
	my $af = $self->{af};

	##############################
	#Get existing max ID
	my $query = "SELECT max(gid) FROM $af->{site__dbtbl_prefix}_CORE_group";
	my $sth;
	eval{
	    $sth = $af->getDB->prepare($query);
	    $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;
	}
	debug_print("add_group: maxgid = $maxid");
	
	##############################
	#Insert a new record
	$query = "insert into $af->{site__dbtbl_prefix}_CORE_group(gid, group_name, members, option_pid) values (?,?,?,?)";
	eval{
	    $sth = $af->getDB->prepare($query);
	    $sth->execute($maxid+1, $group_name, ",", -1);
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB->errstr);
	}

	debug_print("add_group: end.");
	return($maxid+1);
    }

    ########################################################################
    #remove_group
    ########################################################################
    sub remove_group{                  #void
	my $self = shift;
	my $gid = shift;             #arg(1) gid

	debug_print("remove_group: g[$gid]");
	my $af = $self->{af};

	my $query1 = "SELECT option_pid FROM $af->{site__dbtbl_prefix}_CORE_group WHERE gid = ?";
	my $sth1;
	eval{
	    $sth1 = $af->getDB->prepare($query1);
	    $sth1->execute($gid);
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB->errstr);
	}

	my @row1 = $sth1->fetchrow_array;
	my $perm_id = $row1[0];

	my $query2 = "DELETE FROM $af->{site__dbtbl_prefix}_CORE_group WHERE gid = ?";
	my $sth2;
	eval{
	    $sth2 = $af->getDB->prepare($query2);
	    $sth2->execute($gid);
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB->errstr);
	}

	use Affelio::Managing::PermissionManager;
	$af->getPERM->remove_permission_by_pid($perm_id);

	debug_print("remove_group: end.");
    }

    ########################################################################
    #rename_group
    ########################################################################
    sub rename_group{
	my $self = shift;
	my $gid = shift;               #arg(1) gid
	my $new_name = shift;          #arg(2) new_name

	debug_print("rename_group: g[$gid] -> [$new_name]");
	my $af = $self->{af};

	##############################
	#Update DB
	my $query = "update $af->{site__dbtbl_prefix}_CORE_group set group_name = '$new_name' where gid = $gid";
	my $sth;
	eval{
	    $sth = $af->getDB->prepare($query);
	    $sth->execute;
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB->errstr);
	}

	debug_print("rename_group: end.");
    }


    ########################################################################
    #get_member
    ########################################################################
    sub get_member{                    #returns int[]  uids
	my $self = shift;
	my $gid = shift;               #arg(1) gid

	debug_print("get_member: g[$gid]");
	my $af = $self->{af};

	my $query = "SELECT members FROM $af->{site__dbtbl_prefix}_CORE_group WHERE gid = ?";
	my $sth;
	eval{
	    $sth = $af->getDB->prepare($query);
	    $sth->execute($gid);
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB->errstr);
	}

	my @row = $sth->fetchrow_array;

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

	my @member_array = split(",", $row[0]);
	return(@member_array);
    }


    ########################################################################
    #add_member
    ########################################################################
    sub add_member{                  #void
	my $self = shift;
	my $gid = shift;             #arg(1) gid
	my $uid = shift;             #arg(2) uid

	debug_print("add_member: g[$gid] <- u[$uid]");
	my $af = $self->{af};

	##############################
	#retrieve a friend record from DB
	my $query = "SELECT * FROM $af->{site__dbtbl_prefix}_CORE_group WHERE gid = ?";
	my $sth;
	eval{
	    $sth = $af->getDB->prepare($query);
	    $sth->execute($gid); 
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB->errstr);
	}
	my @row = $sth->fetchrow_array;

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

	##############################
	#Check existing member
	my $current_mem = $row[2];
	if($current_mem =~ /,$uid,/){
	    debug_print("add_member: Error: u[$uid] is already in g[$gid]");
	    return;
	}

	##############################
	#Add the new user
	debug_print("add_member: Member($gid) = ($current_mem) (before)");
	my $new_mem = $current_mem . $uid . ",";
	debug_print("add_member: Member($gid) = ($new_mem) (after)");

	##############################
	#Update DB
	$query = "update $af->{site__dbtbl_prefix}_CORE_group set members = '$new_mem' where gid = $gid";
	eval{
	    $sth = $af->getDB->prepare($query);
	    $sth->execute;
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB->errstr);
	}

	debug_print("add_member: end.");
    }


    ########################################################################
    #remove_person_from_all
    ########################################################################
    sub remove_person_from_all{
	my $self = shift;
	my $uid = shift;             #arg(1) uid

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

	db_value_replace($af->getDB,
			 "$af->{site__dbtbl_prefix}_CORE_group",
			 "gid",
			 "members",
			 ",$uid," ,
			 ",," , 
			 );
    }


    ########################################################################
    #remove_member
    ########################################################################
    sub remove_member{                  #void
	my $self = shift;
	my $gid = shift;             #arg(1) gid
	my $uid = shift;             #arg(2) uid

	debug_print("remove_member: g[$gid] u[$uid]");
	my $af = $self->{af};

	my $query = "SELECT members FROM $af->{site__dbtbl_prefix}_CORE_group WHERE gid = ?";
	my $sth;
	eval{
	    $sth = $af->getDB->prepare($query);
	    $sth->execute($gid);
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB->errstr);
	}
	my @row = $sth->fetchrow_array;

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

	debug_print("remove_member: Member($gid) = ($row[0]) (before)");
	$row[0] =~ s/,$uid,/,/;
	debug_print("remove_member: Member($gid) = ($row[0]) (after)");

	my $query2 = "update $af->{site__dbtbl_prefix}_CORE_group set members = '$row[0]' where gid = $gid";
	my $sth2;
	eval{
	    $sth2= $af->getDB->prepare($query2);
	    $sth2->execute;
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB->errstr);
	}

	debug_print("remove_member: end.");
	return;
    }

    ########################################################################
    #get_groups_by_uid
    ########################################################################
    #sub SQL_result get_groups_by_uid(uid)
    #SQL_result (gid, group_name, members, option_pid)
    sub get_groups_by_uid{           #returns SQL result
	my $self = shift;
	my $uid = shift;             #arg(1) uid

	debug_print("get_groups_by_uid: u[$uid]");
	my $af = $self->{af};

	my $query = 
	    "SELECT * FROM $af->{site__dbtbl_prefix}_CORE_group WHERE members like '%,$uid,%'";
	debug_print("get_groups_by_uid: q=[$query]");

	##############################
	#retrieve a friend record from DB
	my $sth;
	eval{
	    $sth = $af->getDB->prepare($query);
	    $sth->execute();
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB->errstr);
	}
	return($sth);
    }

    ########################################################################
    #get_unsubscribing_groups_by_uid
    ########################################################################
    #sub SQL_result get_unsubscribing_groups_by_uid
    #SQL_result (gid, group_name, members, option_pid)
    sub get_unsubscribing_groups_by_uid{           #returns SQL result
	my $self = shift;
	my $uid = shift;             #arg(1) uid

	debug_print("get_unsubscribing_groups_by_uid: u[$uid]");
	my $af = $self->{af};

	my $query = "SELECT * FROM $af->{site__dbtbl_prefix}_CORE_group WHERE members NOT like "
	    ."'%,$uid,%'";

	debug_print("get_unsubscribing_groups_by_uid: q=[$query]");

	##############################
	#retrieve a friend record from DB
	my $sth;
	eval{
	    $sth = $af->getDB->prepare($query);
	    $sth->execute();
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB->errstr);
	}
	return($sth);
    }

    ########################################################################
    #get_all_group_list
    ########################################################################
    #sub SQL_result get_all_group_list
    #result (gid, group_name, members, option_pid)
    sub get_all_group_list{           #returns SQL result
	my $self = shift;

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

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

	return($sth);
    }    

    ########################################################################
    #set_member_by_intarray
    ########################################################################
    sub set_member_by_intarray{      #void
	my $self = shift;            
	my $gid  = shift;            #arg(1) gid
	my $uids_ref = shift;            #arg(2) * uid_array_ref
	my @uids = @$uids_ref;

	debug_print("set_member_by_intarray: g[$gid] uids[@uids]");

	my $uids_str=",";
	while(my $member = pop(@uids)){
	    $uids_str .= $member . ",";
	}

	set_member_by_string($self,$gid, $uids_str);
	debug_print("set_member_by_intarray: end.");
    }

    ########################################################################
    #set_member_by_string
    ########################################################################
    sub set_member_by_string{        #void
	my $self = shift;            
	my $gid  = shift;            #arg(1) gid
	my $uids_str = shift;        #arg(2) uids_str  ex. ",0,1,2,3...20,"

	my $af = $self->{af};
	debug_print("set_member_by_string: g[$gid] uids[$uids_str]");

	##############################
	#Update DB
	my $query = "update $af->{site__dbtbl_prefix}_CORE_group set members = '$uids_str' where gid = $gid";
	my $sth;
	eval{
	    $sth= $af->getDB->prepare($query);
	    $sth->execute;
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB->errstr);
	}

	debug_print("set_member_by_string: end.");
    }

    ########################################################################
    #set_pid
    ########################################################################
    sub set_pid{                     #void
	my $self = shift;            
	my $gid  = shift;            #arg(1) gid
	my $pid  = shift;            #arg(2) pid

	my $af = $self->{af};
	debug_print("set_pid: g[$gid] p[$pid]");

	##############################
	#Update DB
	my $query = "update $af->{site__dbtbl_prefix}_CORE_group set option_pid = $pid where gid = $gid";
	my $sth;
	eval{
	    $sth= $af->getDB->prepare($query);
	    $sth->execute;
	};
	if($@){
	    throw Affelio::exception::DBException($af->getDB->errstr);
	}

	debug_print("set_pid: end.");
    }

    ########################################################################

}#package
1;
