package OneUnified::Session;

# Created on 2007/02/28 by Ray Burkholder
# Copywrite 2007 One Unified

require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(SignInUser);

use strict;

use DBIx::SearchProfiles;
use DBIx::UserDB;

use OneUnified::Const;

sub SignInUser ( $$$$ ) {

  my ( $strErrors, $fldEmailAddress, $fldPassword, $sessionuuid ) = @_;
  #    ref

  my ( $hDB, $hSP, $hUDB );
  my ( $sDbConn, $sDbUser, $sDbPass, $sSearchProfile ) = getDbOUParams();

  my $bValid = 1;

  $hDB = DBI->connect( $sDbConn, $sDbUser, $sDbPass, { RaiseError => 1, AutoCommit => 1 } );

  $hSP = new DBIx::SearchProfiles( $hDB, $sSearchProfile );
  $hUDB = new DBIx::UserDB( $hSP, "userdb", "groupdb" );

  $hUDB ->  scramble_password( 0 );
  my $retval = $hUDB -> user_login( $fldEmailAddress, $fldPassword );

  if ( 0 == $retval ) {
    $$strErrors .= "Sign In Unsuccessful.<br>\n";
    $bValid = 0;
    }
  else {
    my ( $rv, $rc, $row_hash, $sth, $rows );
    my ( $flduuid, $flduid );

    $sth = $hDB->prepare( q{select uuid, uid from sessions where uuid=?} );
    $rv = $sth->execute( $$sessionuuid );
    $sth->bind_columns( \$flduuid, \$flduid );
    $rc = $sth->fetch();
    if ( 0 == $rc ) {
      $sth = $hDB->prepare( q{insert into sessions ( uuid, uid, ts ) values (?,?,now() ) } ) ;
      $rv = $sth->execute( $$sessionuuid, $$retval{uid} );
      }
    else {
      $sth = $hDB->prepare( q{update sessions set uid=?, ts=now() where uuid=? } );
      $rv = $sth->execute( $$retval{uid}, $$sessionuuid );
      }
    }

  $hDB->disconnect;

  return $bValid;
  }


1;

