package Archive::Har::Browser;

use warnings;
use strict;
use Carp();

our $VERSION = '0.11';

sub new {
    my ( $class, $params ) = @_;
    my $self = {};
    bless $self, $class;
    if ( defined $params ) {
        $self->name( $params->{name} );
        $self->version( $params->{version} );
        if ( defined $params->{comment} ) {
            $self->comment( $params->{comment} );
        }
        foreach my $key ( sort { $a cmp $b } keys %{$params} ) {
            if ( $key =~ /^_[[:alnum:]]+$/smx ) {    # private fields
                $self->$key( $params->{$key} );
            }
        }
    }
    return $self;
}

sub name {
    my ( $self, $new ) = @_;
    my $old = $self->{name};
    if ( @_ > 1 ) {
        $self->{name} = $new;
    }
    if ( defined $old ) {
        return $old;
    }
    else {
        return 'Unknown';
    }
}

sub version {
    my ( $self, $new ) = @_;
    my $old = $self->{version};
    if ( @_ > 1 ) {
        $self->{version} = $new;
    }
    if ( defined $old ) {
        return $old;
    }
    else {
        return 'Unknown';
    }
}

sub comment {
    my ( $self, $new ) = @_;
    my $old = $self->{comment};
    if ( @_ > 1 ) {
        $self->{comment} = $new;
    }
    return $old;
}

sub AUTOLOAD {
    my ( $self, $new ) = @_;

    my $name = $Archive::Har::Browser::AUTOLOAD;
    $name =~ s/.*://smx;    # strip fully-qualified portion

    my $old;
    if ( $name =~ /^_[[:alnum:]]+$/smx ) {    # private fields
        $old = $self->{$name};
        if ( @_ > 1 ) {
            $self->{$name} = $new;
        }
    }
    else {
        Carp::croak(
"$name is not specified in the HAR 1.2 spec and does not start with an underscore"
        );
    }
    return $old;
}

sub TO_JSON {
    my ($self) = @_;
    my $json = {
        name    => $self->name(),
        version => $self->version(),
    };
    if ( defined $self->comment() ) {
        $json->{comment} = $self->comment();
    }
    foreach my $key ( sort { $a cmp $b } keys %{$self} ) {
        next if ( !defined $self->{$key} );
        if ( $key =~ /^_[[:alnum:]]+$/smx ) {    # private fields
            $json->{$key} = $self->{$key};
        }
    }
    return $json;
}

1;
__END__
=head1 NAME

Archive::Har::Browser - Represents the browser that created of the HTTP Archive

=head1 VERSION

Version '0.11'

=head1 SYNOPSIS

    use Archive::Har();

    my $http_archive_string = '"log": { "version": "1.1", .... ';
    my $har = Archive::Har->new();
    $har->string($http_archive_string);
    print "Name: " . $har->browser()->name() . "\n";
    print "Version: " . $har->browser()->version() . "\n";
    print "Comment: " . $har->browser()->comment() . "\n";

=head1 SUBROUTINES/METHODS

=head2 new

returns a new Browser object

=head2 name

returns the name of the Browser

=head2 version

returns the version of the Browser

=head2 comment

returns the comment about the Browser

