package Clark04::Data::User;
use strict;
#We're not using this yet...
#use Porkloin::Cookie;
#use Clark04::Data::Data;
use Clark04::Eblocks::Data;
use constant COOKIENAME => "clark04_user";
use Data::Dumper;

sub new() {
	my $class = shift;
	my $cookie = shift;
	my $self = {
		person_id => undef, 
		user_id => undef,
		permissions => undef, 
		editorships => undef, 
		email => undef, 
		firstname => undef, 
		lastname => undef, 
		username => undef, 
		zip => undef
	};
	bless $self, $class;
	$self->load($cookie) if (defined $cookie);
	return $self;
}

sub loadFromDBBySession() {
	my $self = shift;
	my $session = shift || undef;
	if (!$session) {
	    use CGI::Cookie;
	    my %cookies = fetch CGI::Cookie;
	    my $cookie = $cookies{'forclark_session'};
	    if (defined($cookie)) {
		$session = $cookie->value;
	    }
	} 
	if (!$session) {
	    return;
	}
	use Clark04::Eblocks::Data;
	my $dbh = Clark04::Eblocks::DBI::getDBH();
	my $sql = "select u.uid as person_id, u.uid as user_id, u.first_name as firstname, u.last_name as lastname, u.realemail as email, u.nickname as username, pg.group_perms as permissions, up.prefvalue as editorships, u.zip as zip from users u left join userprefs up on u.uid=up.uid and up.prefname='section_editorships', perm_groups pg, sessions s where (s.id = ?) and (s.uid = u.uid) and (u.perm_group = pg.perm_group_id)";
	my $sth = $dbh->prepare($sql);
	$sth->bind_param(1, $session);
	die("Query Failed: $sql ") unless $sth->execute();
	my $row = $sth->fetchrow_hashref();
	foreach (keys %{$row}) {
		$self->{$_} = $row->{$_};
	}
	return 1;
}
sub load() {
    my $self = shift;
    my $cookie = shift;
    $self->loadFromDBBySession($cookie);
}

sub fullURL {
    my $self = shift;
    my $request = shift;
    return 'http://' . $ENV{HTTP_HOST} . $request->uri();
}

# Logs a user in, or redirects them to the login page.
sub assertLogin() {
    my $self = shift;
    my $mason = shift;
    my $request = shift;
    my $url = shift || '/';
    $self->load();
    my $uri = $self->fullURL($request);
    if (!$self->{'person_id'}) {
	$mason->redirect($url);
	die;
    }
}

sub save() {
}

sub hasPermission() {
    my $self = shift;
    my $permission = shift;
    return $self->{'permissions'} =~ /,$permission/;
}

sub getPersonID() {
	my $self = shift;
	return $self->{'person_id'};
}

sub getUserID() {
	my $self = shift;
	return $self->{'user_id'};
}

sub getPermissions() {
	my $self = shift;
	return split(/,/, $self->{'permissions'});
}

sub getEditorships() {
	my $self = shift;
	return split(/,/, $self->{'editorships'});
}

sub getFirst() {
	my $self = shift;
	return $self->{'firstname'};
}

sub getLast() {
	my $self = shift;
	return $self->{'lastname'};
}

sub getUser() {
	my $self = shift;
	return $self->{'username'};
}

sub getEmail() {
	my $self = shift;
	return $self->{'email'};
}



1
