# Edoceo::UserAgent perl module - http://www.edoceo.com
package Edoceo::UserAgent;

#use strict;
use warnings;
use Carp;
use LWP::UserAgent;   # Need to have Crypt::SSLeay installed for https support
use HTML::Form;
use HTTP::Cookies;
use HTTP::Request;

my $_session; # Session Hash
my $_ua; # User Agent
my $_req;
my $_res;

sub new
{
   my $self = {};
   $_ua = LWP::UserAgent->new( requests_redirectable => ['GET','HEAD','POST'], timeout=>30);
   bless($self);
   return $self;
}  

sub get
{
  my $self = shift;
  my $url = shift;
  return $self->_request(HTTP::Request->new(GET => $url));
}

sub post
{
  my $self = shift;
  my $url = shift;
  my $post = shift;
  # Is this how I call this?
  return $self->_request(HTTP::Request->new(POST => $url, $post));
}

sub forms
{
  my $self = shift;
  if (ref($_res) eq 'HTTP::Response')
  {
    return HTML::Form->parse($_res->content,$_res->base);
  }
  return undef;
}

sub _request
{
  my ($self,$req) = @_;
  # Bind IP address
  #if ($session->{ip}) { @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr=>$session->{ip}); }
  #if (0) { print '- IP: '.join(' ',@LWP::Protocol::http::EXTRA_SOCK_OPTS)."\n"; }
  # Make a UserAgent
  $_ua->cookie_jar($session->{cj});
  META_REFRESH:
  $req->header('Host',$req->uri()->host);
  $req->header('Accept','*/*');
  $req->header('Accept-Encoding','gzip, deflate');
  $req->header('Accept-Language','en-us');
  $req->header('Connection','close');
  #$req = $ua->prepare_request($req);
  if ($session->{referer}) { $req->header('Referer',$session->{referer}); }
  $_req = $req;
  $_res = $_ua->request($req);
  # Does this copy my cookies back out?
  #$session->{cj} = $ua->cookie_jar();
  #$session->{Dummy} = "\n>>Dummy<<\n";
  #open FH,">>/tmp/$session->{id}.http";
  #print FH "---------- HTTP Request: ----------\nURL: ".$req->url."\n";
  #print FH $req->headers->as_string;
  #print FH "\n---------- HTTP Response: ----------\nURL: ".$res->base."\n";
  #print FH $res->headers->as_string;
  #print FH "\n";
  #close FH;
  # If gzip encoding then uncompress it
  if (($_res->headers()->header('Content-Encoding')) && ($_res->headers()->header('Content-Encoding') eq 'gzip'))
  {
    $_res->content(Compress::Zlib::memGunzip($_res->content));
  }
  if ($_res->is_success)
  {
    # META_REFRESH?
    if ($_res->content =~ m/<meta\s+http-equiv="?refresh"?\s+content\s*=\s*"(\d*);\s*url=(.*?)"/io)
    {
      sleep($1);
      $req->method('GET');
      $req->url($_res->uri()->host.$2);
      goto META_REFRESH;
    }
  }
  else
  {
    # Should do something else here
    print STDERR "$session->{id} HTTP Error: ".$_res->code." ".$_res->message."\n";
  }
  return $_res;
}  

# End of Edoceo::UserAgent
1;
