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

package pilotBBDBTranslate;

use FileHandle;

use strict;

sub new {
    my $type = shift;
    my $self = {};

    bless($self, $type);

    $self->{'host'} = shift;
    $self->{'file'} = shift;

    $self->{'p2b'} = {};
    $self->{'b2p'} = {};

    $self->readFile();

    return $self;
}

sub readFile {
    my $self = shift;

    
    if ((! defined $self->{'file'}) || 
	(! -f      $self->{'file'})) {
	# Give them the most important stuff.
	$self->addMapping("E-mail", "net");
	$self->addMapping("Title",  "title");
	$self->addMapping("Note",   "notes");
	$self->addMapping("AKA",    "aka");
	$self->addMapping("WWW",    "www");
	return;
    }

    my $FILE = new FileHandle($self->{'file'});
    while (<$FILE>) {
	next if (/^\s*\#/);
	next if (/^\s*\$/);
	chop;

	if (/^\s*([^\s]*)\s+(.*[^\s])/) {
	    $self->addMapping($1, $2);
	}
    }
}

sub writeFile {
    my $self = shift;
    
    my $FILE =new FileHandle(">" .$self->{'file'});

    if (!defined $FILE) {
	$self->{'host'}->output("Unable to rewrite translations file: " .
				$self->{'file'} . "\n");
	return;
    }

    print $FILE "# This file describes the mapping between BBDB fields\n";
    print $FILE "# and pilot fields.\n\n";
    print $FILE "# The format is: <pilot field> <bbdb field>\n";
    print $FILE "# The pilot field may not contain a space,\n";

    my %used;
    foreach my $p (keys %{$self->{'p2b'}}) {
	print $FILE $p . " " . $self->{'p2b'}{$p} . "\n";
	$used{$self->{'p2b'}{$p}} = 1;
    }
    foreach my $b (keys %{$self->{'b2p'}}) {
	next if (defined $used{$b});
	print $FILE $self->{'b2p'}{$b} . " " . $b . "\n";
    }
}

sub addMapping {
    my $self = shift;
    my $pilot = shift;
    my $bbdb = shift;
    
    
    if (! defined $self->{'p2b'}{$pilot}) {
	$self->{'p2b'}{$pilot} = $bbdb;
    }

    if (! defined $self->{'b2p'}{$bbdb}) {
	$self->{'b2p'}{$bbdb} = $pilot;
    }
}

sub finish {
    my $self = shift;
}

sub getForBBDB {
    my $self = shift;
    my $pilot = shift;

    return $self->{'p2b'}{$pilot} || $pilot;
}

sub getForPilot {
    my $self = shift;
    my $bbdb = shift;

    # hack for old mapping scheme...
    return $' if ($bbdb =~ m/pilot-field-/);
    return $' if ($bbdb =~ m/pilot-phone-/);

    return $self->{'b2p'}{$bbdb} || $bbdb;
}

sub getBBDBName {
    my $self = shift;
    my $pbbdb = shift;
    my $field = shift;

    my $name;
    if ($field =~ m/^Field.:(.)/) {
	my $idx = $1;
	$name = $pbbdb->{'phoneLabels'}[$idx];
    } elsif ($field =~ m/^Custom(.)/) {
	my $idx = $1; $idx--;
	$name = $pbbdb->getCustLabel($idx);
    } else {
	$name = $field;
    }

    if (defined $self->{'p2b'}{$name}) {
	return $self->{'p2b'}{$name}
    } else {
	return $name;
    }
}

1;
