#------------------------------------------------------------------------------
#   $Date: 2001/11/04 13:17:55 $
#   RCS: $Id: bbdbPhone.pm,v 1.1.1.1 2001/11/04 13:17:55 tdeweese Exp $
#------------------------------------------------------------------------------

package bbdbPhone;

use strict;

use bbdb::bbdb;

sub new {
    my $type = shift;
    my $self = {};
    my $str  = shift;
    my $ver  = shift || $bbdb::DEFAULT_VERSION;

    bless ($self, $type);

    $self->parse($str, $ver);
    $self;
}

sub parse
{
    my $self = shift;
    my $str = shift;
    my $ver  = shift || $bbdb::DEFAULT_VERSION;

    my ($title, $area, $exch, $num, $ext);
    ($title, $area, $exch, $num)=
      ($str =~ /^\"((?:[^\\\"]|\\.)*)\"\s+(\d+)\s+(\d+)\s+(\d+)/);

    ## didn't match above so it's two strings...
    if (defined $area) 
      {
	## Extension may be 'nil'...
	if ($' =~ m/(\d+)/) {
	  $ext = $1;
	}

	$self->{'title'} = $title;
	if ((defined $area) && ($area ne "0")) {
	  $self->{'area'} =  bbdb::mkStr($area);
	}

	$self->{'exch'} =  bbdb::mkStr($exch);
	$self->{'num'} =   bbdb::mkStr($num);

	if ((defined $ext) && ($ext ne "0")) {
	  $self->{'ext'} =   bbdb::mkStr($ext);
	}
      }
    else 
      {
	$str =~ /^\"((?:[^\\\"]|\\.)*)\"\s+\"((?:[^\\\"]|\\.)*)\"$/;
	($title, $num) = ($1, $2);

	$self->{'title'} = $title;
	$self->{'num'} =   $num;
      }

    $self;
}

sub toString
{
  my $self = shift;
  return $self->{'title'} . ": " . $self->phoneString();
}

sub phoneString
{
  my $self = shift;

  if (defined $self->{'exch'})
    {
      my $ret;
      $ret = sprintf ("(%03d) ",$self->{'area'}) if (defined $self->{'area'});
      $ret .= sprintf ("%03d-%04d", $self->{'exch'}, $self->{'num'});

      $ret .= " x" . $self->{'ext'} if (defined $self->{'ext'});
      return $ret;
    }

  return  $self->{'num'};
}

sub print
{
    my $self = shift;
    my $file = shift || \*STDOUT;

    print $file $self->toString() . "\n";
}

sub ePStr
{
    my $self = shift;
    my $ver  = shift || $bbdb::DEFAULT_VERSION;

    my $ret = "[";
    $ret .= bbdb::eStr($self->{'title'}) . " ";
    if (not defined $self->{'exch'}) 
      {
	$ret .= bbdb::eStr($self->{'num'});
      }
    else
      {
	if (defined $self->{'area'}) {
	  $ret .= sprintf("%03d ", $self->{'area'});
	} else {
	  $ret .= "0 ";
	}

	$ret  .= sprintf("%03d %04d ", $self->{'exch'}, $self->{'num'});
	
	if (defined $self->{'ext'}) {
	  $ret .= $self->{'ext'};
	} else {
	  $ret .= "nil";
	}
      }
    
    return $ret . "]";
}

1;
