###################################################################

package KoLBot::KMail;
 
# Copyright (c) 2004 Alan W. Mahoney. All rights reserved. 
# This program is free software.  You may modify and/or 
# distribute it under the same terms as Perl itself.  
# This copyright notice must remain attached to the file.  
#

use warnings;
use strict;

use KoLBot;
use KoLBot::Items;

use Carp;

BEGIN 
{
  use Exporter ();
  our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS, $ID);

  $VERSION     = 0.5;
  $ID          = '$Id: KMail.pm 125 2006-02-23 20:05:45Z alan $';

  @ISA         = qw(Exporter);
  @EXPORT      = qw( );
  %EXPORT_TAGS = ( );

  @EXPORT_OK   = qw();
}

our @EXPORT_OK;

##########################################
## Overloads
##########################################

use overload q("") => \&as_string;

##########################################
## element access
##########################################

for my $field (qw( time
		   user
		   user_id
		   message
 		   rawmsg
		   id
		   meat
		   item_id
		   item_name
		   number
		   type
		   item_db
		   )) {
  no strict "refs";
  *$field = sub {
    my $self = shift;
    $self->{$field} = shift if @_;
    return $self->{$field};
  }
}

##########################################
## Constructor:
##########################################

sub new {
  my $invocant = shift;
  my $class = ref($invocant) || $invocant;
  my $bot = { type => 'kmail',
	      @_ };
  if(ref($bot->{item_id}) ne 'ARRAY') {
    $bot->{item_id} = [$bot->{item_id}];
    $bot->{number} = [$bot->{number}];
  }

  bless $bot, $class;
}

##########################################
## The rest
##########################################

sub as_string {
  my $kmail = shift;
  my $str = '';

  my ($sec,$min,$hour,$mday,$mon,$year) = KoLBot::kmailtime($kmail->time);
  my @months = ('Jan','Feb','Mar','Apr','May','Jun','Jul',
		'Aug','Sep','Oct','Nov','Dec');

  $str .= "From: " . $kmail->user . " (" . $kmail->user_id . ")\n";
  $str .= "Id: " . $kmail->id . "\n";
  $str .= "Date: " . " $mday " . $months[$mon] . " " . ($year+1900)
    . " $hour:" . (($min<10) ? '0': '') . "$min\n";
  $str .= "Meat: " . $kmail->meat . "\n";

  $str .= " Items:\n";

  for (0..$#{$kmail->number}) {
    if($kmail->item_db
       &&
       !exists($kmail->item_db->by_id->{$kmail->item_id->[$_]})) {
      die "Can't find " . $kmail->item_id->[$_];
    }

    $str .= $kmail->number->[$_] . "@" . $kmail->item_id->[$_];
    $str .= ' ' . $kmail->item_db->by_id->{$kmail->item_id->[$_]}->name
      if($kmail->item_db);
    $str .= "\n";
  }
  $str .= "---------\n";
    
  $str .= $kmail->message;

  return $str;
}

END {} ;

1;
