# Format.pm
# Author: Noah Friedman <friedman@splode.com>
# Created: 1999-11-17
# Public domain.

# $Id: Format.pm,v 1.3 2000/02/11 11:38:15 friedman Exp $

package NF::DBI::Format;
use DBI::Format;
use strict;

use Exporter;
use vars qw($VERSION @ISA @EXPORT_OK);
$VERSION     = 1.00;
@ISA         = qw(Exporter);
@EXPORT_OK   = qw(setup_fh header row trailer);


sub new
{
  my $class = shift;
  my $self = (@_ == 1) ? { %{shift()} } : { @_ };
  bless ($self, (ref($class) || $class));
  $self;
}

sub setup_fh ($;$)
{
  my ($self, $fh) = @_;
  $fh ||= *STDOUT{IO};
  if ($fh !~ /=/) {	# not blessed
    require FileHandle;
    bless $fh => "FileHandle";
  }
  return $fh;
}

sub header
{
  return DBI::Format::Box::header (@_);
}

sub row ($$)
{
  my($self, $orig_row) = @_;
  my $i = 0;
  my $col;
  my $widths = $self->{'widths'};
  my @row = @$orig_row; # don't mess with the original row
  map
    {
      if (!defined($_))
        {
          $_ = 'NULL';
        }
      else
        {
          $_ =~ s/\n/\\n/g;
          $_ =~ s/\t/\\t/g;
          $_ =~ s/[\000-\037\177-\237]/./g;
        }
      if (length($_) > $widths->[$i])
        {
          $widths->[$i] = length($_);
        }
      ++$i;
    } @row;
  push @{$self->{data}}, \@row;
}

sub trailer ($)
{
  my ($self) = @_;
  my $widths = delete $self->{'widths'};
  my $right_justify = delete $self->{'right_justify'};
  my $sth  = $self->{'sth'};
  my $data = $self->{'data'};
  $self->{'rows'} = @$data;

  my $format_sep   = '+';
  my $format_names = '|';
  my $format_rows  = '|';
  for (my $i = 0;  $i < $sth->{'NUM_OF_FIELDS'};  $i++)
    {
      $format_sep   .= ('-' x ($widths->[$i]+2)) . '+';
      $format_names .= sprintf(" %%-%ds|", $widths->[$i]+1);
      $format_rows  .= sprintf(" %%"
                               . ($right_justify->[$i] ? "" : "-") . "%ds |",
                               $widths->[$i]);
    }
  $format_sep   .= "\n";
  $format_names .= "\n";
  $format_rows  .= "\n";

  my $fh = $self->{'fh'};
  $fh->print($format_sep);
  $fh->print(sprintf($format_names, @{$sth->{'NAME'}}));
  $fh->print($format_sep);
  foreach my $row (@$data)
    {
      $fh->print(sprintf($format_rows, @$row));
      #$fh->print($format_sep);
    }
  $fh->print($format_sep);

  $fh   = delete $self->{'fh'};
  $sth  = delete $self->{'sth'};
  my $rows = delete $self->{'rows'};
  $fh->print("[$rows rows of $sth->{NUM_OF_FIELDS} fields returned]\n");
}

1;
