package Easy::Plugin::User;

use strict;
use Easy::Item;
use Easy::Helpers;
use CSL::DBs;
use CSL::Pg;
#use CSL::PlRPC_Krb5;
use DBI;
#use Data::Dumper;
my $do_picture = 0;

sub get_query_flags
{
    return ('-u' => \&do_user,
	    '-p' => \&do_user_by_personid,
	    '-px' => \&do_user_xwalk_by_personid,
	    '-n' => \&do_user_by_netid,
	    '-nx' => \&do_user_xwalk_by_netid,
	);
}

sub get_query_regexps
{
    # 10 or 11 digit numbers will work.
    return ('\d{10,11}' => \&do_user);
}

sub get_usage
{
    return ('-u ( <username> | <id number> )' => "Info on a user",
	    '-p <hr person id>' => "Info on a user by HR Person ID",
	    '-px <hr person id>' => "Crosswalk Info on a user by HR Person ID",
	    '-n <netid>' => "Info on a user by NetID",
	    '-nx <netid>' => "Crosswalk Info on a user by NetID",
	);
}


sub do_user_xwalk_by_personid
{
    my ($pid) = @_;
    # Connect to the database
    my ($dbh, $pb) = &_db_connect;

    my $query = $dbh->prepare("select * from id_crosswalk_uwmsn where hr_person_id = ?");
    $query->execute($pid);
    my $row = $query->fetchrow_hashref;
    return Easy::Item->new(title => $pid,
			   text => "User not found by HR Person Id")
	unless ($row);
    $query->finish;
    
    return do_user($row->{'univid'}, $row);
}

sub do_user_by_personid
{
    my ($pid) = @_;
    # Connect to the database
    my ($dbh, $pb) = &_db_connect;

    my $query = $dbh->prepare("select univid from id_crosswalk_uwmsn where hr_person_id = ?");
    $query->execute($pid);
    my $row = $query->fetchrow_arrayref;
    return Easy::Item->new(title => $pid,
			   text => "User not found by HR Person Id")
	unless ($row);
    $query->finish;
    return do_user($row->[0]);
}

sub do_user_by_netid
{
    my ($nid) = @_;
    # Connect to the database
    my ($dbh, $pb) = &_db_connect;

    my $query = $dbh->prepare("select univid from id_crosswalk_uwmsn where netid = ?");
    $query->execute(uc($nid));
    my $row = $query->fetchrow_arrayref;
    return Easy::Item->new(title => $nid,
			   text => "User not found by NetID")
	unless ($row);
    $query->finish;
    return do_user($row->[0]);
}

sub do_user_xwalk_by_netid
{
    my ($nid) = @_;
    # Connect to the database
    my ($dbh, $pb) = &_db_connect;

    my $query = $dbh->prepare("select * from id_crosswalk_uwmsn where netid = ?");
    $query->execute(uc($nid));
    my $row = $query->fetchrow_hashref;
    return Easy::Item->new(title => $nid,
			   text => "User not found by NetID")
	unless ($row);
    $query->finish;
    return do_user($row->{'univid'}, $row);
}

sub do_user
{
    my ($user, $xwalk) = @_;
    
    # Connect to the database
    my ($dbh, $pb) = &_db_connect;

    # <hack type='restrict access to labstaff' req='[CSL #312120]'>
    my $query = $dbh->prepare("select labstaff from people where uid = ?");
    $query->execute($<);	# $UID if we used English
    my $row = $query->fetchrow_hashref;
    return Easy::Item->new(title => "Unauthorized",
                           text => "Access granted to labstaff only")
        unless ($row->{labstaff} == 1);
    # </hack>

    # Bar Code Reader modification (Oct 4, 2011: babb)
    # Truncate to 10 digits if its 11 digits (e.g. barcode scanner)
    if($user =~ /^\d{11}$/)
    {
        $user = substr $user, 0, 10;
    }

    # Get the ID if it's a login
    my $login;
    if ($user !~ /^\d{10}$/)
    {
	my $query = $dbh->prepare("select univid from people where login = ?");
	$query->execute($user);
	my $row = $query->fetchrow_arrayref;

	return Easy::Item->new(title => $user,
			       text => "User not found")
	    unless ($row);

	$login = $user;
	($user) = $row->[0];
	$query->finish;
    }
    # Get the username
    else
    {
	
	my $query = $dbh->prepare("select login from people where univid = ?");
	$query->execute($user);
	my $row = $query->fetchrow_arrayref;

	return Easy::Item->new(title => $user,
			       text => "User not found")
	    unless ($row);

	($login) = $row->[0];
	$login ||= "NO LOGIN";
	$query->finish;
    }

    # Get a list of classes
    my $query = $dbh->prepare("select * from csorp.enrolled where univid = ? order by cid");
    $query->execute($user);

    # Status and type
    my %status = (N => 'Enrolled',
		  A => 'Recent Add',
		  D => 'Dropped');
    my %type = (N => 'Normal',
		I => 'Incomplete');

    my @rows;
    while (my $row = $query->fetchrow_hashref)
    {
	# Reformat
	$row->{cid} =~ s/(\d{3})(\d{3}).*/$1-$2/;
	$row->{status} = $status{$row->{status}};
	$row->{type} = $type{$row->{type}};
	$row->{date} =~ s/\s\d{4}.*//;

	push @rows, [ $row->{cid}, $row->{status}, $row->{type},
		      $row->{date} ];
    }

    # Some general user attributes
    $query = $dbh->prepare("select * from people where univid = ?");
    $query->execute($user);
    my $row = $query->fetchrow_hashref;
#    print Dumper($row);

    my $curaddress = "";
    $curaddress .= $row->{curaddr1} if $row->{curaddr1};
    $curaddress .= " " . $row->{curaddr2} if $row->{curaddr2};
    $curaddress .= " " . $row->{curzip} if $row->{curzip};

    my $uwoffice = "";
    $uwoffice .= $row->{uwbuilding} if $row->{uwbuilding};
    $uwoffice .= " " . $row->{uwoffice} if $row->{uwoffice};

    my %attributes = (login => $row->{login},
		      univid => $row->{univid},
		      name => "$row->{firstname} $row->{lastname}",
		      office => $uwoffice, #$row->{uwoffice},

                      # current address/phone
                      curaddress => $curaddress,
                      curphone => $row->{curphone},
                      altphone => $row->{altphone},

                      # uw info
                      uwdept => $row->{uwdept},
#                      uwoffice => $uwoffice,
                      uwphone => $row->{uwphone},

                      # extra
                      notes => $row->{pnotes},
                      extraafsquota => $row->{extraafsquota},
                      
		      );
    my @attribute_order = qw(name login univid status office curaddress curphone altphone uwdept uwphone notes extraafsquota);

    if (defined($xwalk) && $xwalk) {
	foreach my $a ('netid', 'hr_person_id', 'isis_campus_id', 'pvi') {
	    push (@attribute_order, $a);
	    $attributes{$a} = $xwalk->{$a};
	}
    }

    # Figure out the status
    my %status_trans = (csmajor => "cs major",
			grad => "grad student",
			cs_student => "student",
			stat_student => "student",
			alum => "alumni",
			faculty => "faculty",
			vfaculty => "visiting faculty",
			lecturer => "instructor",
			secretary => "biz ofc staff",
			secondmasters => "secondmasters",
			upl => "upl",
			special => "special",
			program => "program",
			statperson => "stat person",
			ta => "ta",
			ra => "ra",
			pa => "pa",
			lte => "lte",
			labstaff => "labstaff",
			staff => "staff",
			onleave => "onleave",
			c => "courtesy",
                        E => "emeritus",
                        L => "ex-labbie",
                        J => "joint-appoint",
                        P => "project",
                        o => "offsite-collab",
                        F => "fellow",
                        X => "cs certificate student",
                        S => "student staff",
			G => "grader",
			M => "PMP",
			N => "PCP",
                        D => "DSI",
                        I => "iSchool",
                        C => "CDIS",
                        T => "Teaching Faculty",
                        p => "Postdoc",
                        s => "Student Services",
                        u => "UA",
                        '-' => 'no status remaining',
                        );

    # map {$row->{uc $_} = 1} (split //, $row->{status});
    map {$row->{$_} = 1} (split //, $row->{status});
    
   # $row->{$row->{status}} = 1;
    $attributes{status} = join(", ", map { $status_trans{$_} } 
			       sort grep { $row->{$_} == 1 } 
			       keys %status_trans);

    my %class = (auxheadings => ['class',
			      'status',
			      'type',
			      'date'],
		 auxlist => \@rows)
	if @rows;


    # Figure out their bits
    # due to db changes, this has become somewhat redundant
    my $query = $dbh->prepare("select a.machine, a.sponsor, a.accountcomment, m.prime_user from accounts a, people p, machines m where a.uid = p.uid and a.machine = m.cpuname and p.login = ? order by machine");
    $query->execute($login);

    my @arows;
    my %prime = ($login => "Yes");
    while (my $row = $query->fetchrow_hashref)
    {
        push @arows, [ $row->{machine}, $row->{sponsor}, $prime{$row->{prime_user}}, $row->{accountcomment} ];
    }

    my %accounts = (headings => ['account', 'sponsor', 'prime user', 'comment'], list => \@arows) if @arows;

    return Easy::Item->new(title => $login,
			   attributes => \%attributes,
			   attributes_order => \@attribute_order,
			   %accounts,
			   %class);
}

# Set up the database connection and phrasebook here
# in one place...instead of many times up there
sub _db_connect {
  my $dbh = DBI->connect($CSL::DBs::csdb)
    or die "Could not connect to CSDB: $!";
  $dbh->do("set search_path to csdb");
  $dbh->{ChopBlanks} = 1;


  # User.pm doesn't use $pb
  my $pb = '';
  # # I will have to make this a CSL-ism somehow
  # my $pb = new Class::Phrasebook::SQL(undef, "!!LIBDIR!!/Easy/easy.pbk")
  #   or die "Could not open SQL Phrasebook: $!";
  # $pb->load("easy_queries")
  #  or die "Could not load queries, check your Phrasebook XML";

  return ($dbh, $pb);
}


1;


