package UserAgent;
# $Id: UserAgent.pm,v 1.4 2000/11/08 16:50:58 tom Exp $
################################################################

=head1 NAME

UserAgent - object class of HTTP_USER_AGENT

=head1 SYNOPSIS

  use UserAgent;
  my $ua = new UserAgent;
  $ua->Set($ENV{'HTTP_USER_AGENT'});
  print $ua->name_version, $ua->proxy,.....;

=head1 DESCRIPTION

if you want to set any value,
you muse use Set() function.

=head1 BUGS

for MSIE,
  "Mozilla/4.0 (compatible; MSIE 4.01; Windows 95)"
which includes 'compatible' is converted to
  "MSIE/4.01 (Mozilla/4.0 compatible; Windows 95)"

=cut

use strict;
use ObjectTemplate;
use CGI::Tools;

use vars qw(@ISA);

@ISA = qw(ObjectTemplate);

attributes qw(fullname name version name_version info proxy);

################################################################
sub initialize($)
{
    my $self = shift;

    $self->Set($self->fullname) if $self->fullname;
    $self->SUPER::initialize;
}

sub Set($$)
{
    my ($self, $full) = @_;

    # escape reference entity
    $full = Escape($full);
   
    # proxy
    $full =~ s/ +via +(.*)$//;
    my $proxy = $1;

    # extension information
    my ($name_version, $info) = $full =~ /^(.*?)\s*\((.*)\)$/;
    $name_version ||= $full;

    # processing for MSIE
    # Mozilla/4.0 (compatible; MSIE 4.01; Windows 95) ->
    # MSIE/4.01 (Mozilla/4.0 compatible; Windows 95);
    if ($info =~ /^compatible; MSIE ([\d\.]+); (.*)$/){
	my ($msie_ver, $ext_info) = ($1, $2);
	$info = "$name_version compatible; $ext_info";
	$name_version = "MSIE/$msie_ver";
    } elsif ($info =~ m!^compatible; *([^/]+)/([\d\.]+); *(.*)$!){
	# Mozilla/4.0 (compatible; MuscatFerret/2.0; http://www.webtop.com/)->
	# MuscatFerret/2.0 (Mozilla/4.0 compatible; http://www.webtop.com/)
	my ($name, $version, $ext_info) = ($1, $2, $3);
	$info = "$name_version compatible; $ext_info";
	$name_version = "$name/$version";
    }

    # name and version
    my ($name, $version, $tmp) = $name_version =~ m!([^/]*?)/([^/\s]*)[/ ]*(.*)$!;
    $name ||= $name_version;
    if ($tmp){
	$name_version = "$name/$version";
	if ($info){
	    $info = "$tmp $info";
	} else {
	    $info = $tmp;
	}
    }
    
    # set these values
    $self->fullname($full);
    $self->name($name);
    $self->version($version);
    $self->name_version($name_version);
    $self->info($info);
    $self->proxy($proxy);
    return $self;
}
1;
