#!/usr/bin/perl

#use utf8;
use strict;
use CGI;

use Opals::Context;#use MARC::File::USMARC;


use LWP::Simple;
my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }


my $cgi = CGI->new;
my $input = $cgi->Vars();
my $uid=$input->{'uid'};
my $imgId=$input->{'id'};
my ($img,$mimeType)=(undef,undef);
if(defined $uid && $uid>0){
     ($img,$mimeType)=getUserImg_byUid($dbh,$uid);

}
elsif(defined $imgId && $imgId>0){
     ($img,$mimeType)=getUserImg_byId($dbh,$imgId);
}

if(defined $img && length($img)>0){
    print $cgi->header(-type => '$mimeType' );
    print $img;
}


else{
    print $cgi->header(-type => 'image/jpeg' );
    my $rootDir       = Opals::Context->config('rootDir');
    my $noImgPath = "$rootDir/htdocs/theme/opals/image/noUserImg.png";
    open NOIMG, "<$noImgPath";
    while(<NOIMG>){
        print $_;
    }
    close NOIMG;
    
}

sub getUserImg_byUid{
    my ($dbh, $uid)=@_;
    my $sth = $dbh->prepare("select thumbnail,mimeType from opl_userImg where uid= ? order by id desc limit 1 ");
    $sth->execute($uid);
    if(my ($img,$mimeType) = $sth->fetchrow_array){
        return ($img,$mimeType);
    }
    else{
        return (undef,undef);
    }


}
sub getUserImg_byId{
    my ($dbh, $id)=@_;
    my $sth = $dbh->prepare("select thumbnail,mimeType from opl_userImg where id= ? ");
    $sth->execute($id);
    if(my ($img,$mimeType) = $sth->fetchrow_array){
        return ($img,$mimeType);
    }
    else{
        return (undef,undef);
    }

}
