#------------------------------------------------------------------------------
#   $Date$
#   RCS: $Id$
#------------------------------------------------------------------------------

package SyncBBDB;

use Carp;
use strict;

use SyncUtil::PilotMgrHost;
use SyncUtil::SyncEngine;
use SyncUtil::localHash;
use SyncBBDB::localBBDB;
use SyncBBDB::pilotBBDB;
use SyncBBDB::pilotBBDBTranslate;

my ($VERSION) = cvsversion("2.6", '$Revision$');
my $OBJECT;

sub cvsversion {
    my ($version, $revision) = @_;
    $revision =~ s/^\$Revision:? ?//;
    $revision =~ s/ ?\$$//;
    $version .= "-cvs-$revision" if $revision;
    $version;
}

sub new {
  my $type = shift;
  my $self =	{};
  
  $self->{'dir'} = shift;

  bless ($self, $type);
  $self;
}

sub conduitInit {
  my $self = new SyncBBDB(shift);
  $OBJECT = $self;

  if (! -f "$self->{'dir'}/control") {
      # file doesn't exist so provide defaults.
    $self->{'control'}{'presync'}  = 
      "gnuclient -batch -eval \"(bbdb-save-db)\" > /dev/null";
    $self->{'control'}{'postsync'} =
      ( "gnuclient -q -batch -eval \"(let ((bbdb-auto-revert-p 't)) " .
	"(bbdb-records))\"");
    $self->{'control'}{'bbdbfile'} = "$ENV{'HOME'}/.bbdb";

    return;
  }

  open(C,"<$self->{'dir'}/control") || return;

  my @fields = ('presync', 'postsync', 'bbdbfile');
  while(<C>) {
    chomp;
    next if ($_ =~ m/^\#/);   # Comment
    next if ($_ =~ m/^\s*$/); # Blank line
    
    if ($_ =~ m/([^=]*)=(.*)/) {
	$self->{'control'}{$1} = $2;
	next;
    }

    $self->{'control'}{shift(@fields)} = $_;
    last if (! scalar(@fields));
  }

  @fields = ('presync', 'postsync', 'bbdbfile');
  $self->{'control'}{shift(@fields)} = ""
      if (!defined $self->{'control'}{shift(@fields)});

  close(C);
}

sub conduitInfo {
  return {
	  'version' => $VERSION,
	  'author' => 'Thomas DeWeese',
	 };
}


sub conduitConfigure {
  my $name = shift;
  my $wm   = shift;
  
  my $self = $OBJECT;
  unless (defined $self->{'config'})
    {
      $self->{'config'} = $wm->Toplevel('-title' => $name);
      $self->{'config'}->transient($wm);
      my ($frame, $subfr, $obj);

      $frame = $self->{'config'};
      $obj = $frame->Label('-text' => 
			   ("SyncBBDB v$VERSION\n" . 
			    "Thomas DeWeese\n"));
      $obj->pack('-side' => 'top');
      
      my $dismiss = $frame->Button('-text'    => 'Dismiss', 
				   '-command' => sub {
				     my $self = $OBJECT;
				     $self->savePrefs();
				     $self->{'config'}->withdraw();
				   });

      $subfr = $frame->Frame(-relief => "sunken", -bd => 4);
      $obj = $subfr->Label('-text' => "BBDB file: ");
      $obj->pack('-side' => "left", '-anchor' => "nw", '-fill' => "x");

      $obj = $subfr->Entry('-textvariable' => 
			   \$self->{'control'}{'bbdbfile'},
			   '-relief' => "sunken", '-width' => 60);
      $obj->pack('-side' => "left", '-anchor' => "w");

      $frame = $self->{'config'}->Frame(-relief => "sunken", -bd => 4);
      $obj = TkUtils::Label($frame, "Pre/Post Sync Scripts");
      $obj->pack(-anchor => "c");
      $subfr->pack('-anchor' => "c", '-fill' => "x");

      $subfr = $frame->Frame;
      $obj = $subfr->Label('-text' => "Pre-Sync script: ");
      $obj->pack('-side' => "left", '-anchor' => "nw", -fill => "x");

      $obj = $subfr->Entry('-textvariable' => \$self->{'control'}{'presync'},
			   '-relief' => "sunken", '-width' => 60);
      $obj->pack('-side' => "left", '-anchor' => "w");

      $obj = TkUtils::Button
	($subfr, "Run Now",
	 sub{ 
	   if ($self->{'control'}{'presync'}) {
	     $dismiss->configure(-state => "disabled");
	     my ($curs) = ($self->{'config'}->cget("-cursor"));
	     $self->{'config'}->configure(-cursor => "watch");
	     $self->{'config'}->update;
	     my $result = `$self->{'control'}{'presync'}`;
	     $self->{'config'}->configure(-cursor => $curs);
	     $dismiss->configure(-state => "normal");
	   } 
	 });
      $obj->pack(-side => "left", -anchor => "w", -fill => "x");
      $subfr->pack(-anchor => "e");

      $subfr = $frame->Frame;
      $obj = $subfr->Label('-text' => "Post-Sync script: ");
      $obj->pack('-side' => "left", '-anchor' => "nw", -fill => "x");

      $obj = $subfr->Entry('-textvariable' => \$self->{'control'}{'postsync'},
			   '-relief' => "sunken", '-width' => 60);
      $obj->pack('-side' => "left", '-anchor' => "w");
      $obj = TkUtils::Button
	($subfr, "Run Now",
	 sub{ 
	   if ($self->{'control'}{'postsync'}) {
	     $dismiss->configure(-state => "disabled");
	     my ($curs) = ($self->{'config'}->cget("-cursor"));
	     $self->{'config'}->configure(-cursor => "watch");
	     $self->{'config'}->update;
	     my $result = `$self->{'control'}{'postsync'}`;
	     $self->{'config'}->configure(-cursor => $curs);
	     $dismiss->configure(-state => "normal");
	   } 
	 });
      $obj->pack(-side => "left", -anchor => "w", -fill => "x");
      $subfr->pack('-anchor' => "e");
      $frame->pack(-side => 'top', -fill => 'x');

      $dismiss->pack('-side'   => 'left', '-expand' => 1, '-anchor' => 'c');
      
      PilotMgr::setColors($self->{'config'});
    }
  
  $self->{'config'}->Popup('-popanchor'  => 'c', 
			   '-overanchor' => 'c',
			   '-popover'    => $wm);
}

sub conduitQuit {
  my $self = $OBJECT;
  $self->savePrefs();
}

sub conduitSync {
  my $self = $OBJECT;
  my $name = shift;
  my $dlp  = shift;
  my $info = shift;

  my $bbdb = $self->getBBDB();
    
  if ($self->{'control'}{'presync'}) {
    $dlp->watchdog(20);
    my $result = `$self->{'control'}{'presync'}`;
    $dlp->watchdog(0);

    PilotMgr::msg("Presync: " . $result) if ($result);
  }

  $self->{'host'}   = new PilotMgrHost($name, $dlp, $info);

  $self->{'translate'} = new pilotBBDBTranslate($self->{'host'},
						$self->{'dir'}."/translate");

  $self->{'hash'}    = new localHash($self->{'host'});
  $self->{'localDB'} = new localBBDB($self->{'host'}, $self->{'hash'}, 
				     $bbdb,
				     $self->{'translate'});
  $self->{'pilotDB'} = new pilotBBDB($self->{'host'}, $dlp, $info, 
				     $self->{'hash'},
				     $self->{'translate'});

  my $engine  = new SyncEngine($self->{'host'}, 
			       $self->{'localDB'}, 
			       $self->{'pilotDB'});

  

  $engine->start();

  $self->{'hash'}->finish();
  $self->{'host'}->finish();
  $self->{'translate'}->finish();
  $self->{'translate'}->writeFile();

  if ($self->{'control'}{'postsync'}) {
    $dlp->watchdog(20);
    my $result = `$self->{'control'}{'postsync'}`;
    $dlp->watchdog(0);

    PilotMgr::msg("Postsync: " . $result) if ($result);
  }
}

sub getBBDB {
  my $self = shift;
  return $self->{'control'}{'bbdbfile'};
}

sub savePrefs {
  my $self = shift;
  
  open(C, ">$self->{'dir'}/control") || 
    croak "Unable to create/write to $self->{'dir'}/control";

  print C "# The first two entries are the pre & post sync commands, \n";
  print C "# respectively.\n";
  print C "# The next entry is the location of your bbdb file\n";
  print C "# (ussually ~/.bbdb)\n\n";
  foreach my $key (keys %{$self->{'control'}}) {
      print C $key . "=" . $self->{'control'}{$key} . "\n";
  }

  close(C);
}

1;
