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

package KoLBot::Recipes;
 
# 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::Recipe;

use POSIX qw( floor );

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

  $VERSION     = 0.5;
  $ID          = '$Id: Recipes.pm 92 2005-03-15 02:22:29Z alan $';

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

  @EXPORT_OK   = qw();
}

our @EXPORT_OK;

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

for my $field (qw( 
		   by_product

		   by_product_action
		   by_action_product
		   by_reagent_action
		   all
		   )) {
  no strict "refs";
  *$field = sub {
    my $self = shift;
    $self->{$field} = shift if @_;
    return $self->{$field};
  }
}

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

# Needs to be called with a full config hashref.  See examples.

sub new {
  my $invocant = shift;
  my $class = ref($invocant) || $invocant;
  my $recipes = { @_ };

  # points to array of recipes, new way
  $recipes->{by_reagent_action} = {};
  $recipes->{by_product_action} = {};
  $recipes->{all} = [];

  bless $recipes, $class;
}

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

sub add {
  my $recipes = shift;
  my $r = shift;

  for(@{$r->reagents}) {
    $recipes->by_reagent_action->{$_} ||= {};
    $recipes->by_reagent_action->{$_}->{$r->action} ||= [];
    push @{$recipes->by_reagent_action->{$_}->{$r->action}},$r;
  }
  for(@{$r->products}) {
    $recipes->by_product_action->{$_} ||= {};
    $recipes->by_product_action->{$_}->{$r->action} ||= [];
    push @{$recipes->by_product_action->{$_}->{$r->action}},$r;
  }
  push @{$recipes->{all}},$r;
}

sub init {
  my $recipes = shift;

  open FILE,"<",$recipes->{config}->{file}
    or die "Can't open the file " . $recipes->{config}->{file};

  while (<FILE>) {
    chomp;
    /^\s*$/ and next;
    /^#/ and next;
    my ($products,$action,$reagents)
      = /^([\d\s]*?)\s*(\w+)\s*([\d\s]*?)$/
      or die "Can't read line $_";

    my @products = split(/\s+/,$products);
    my @reagents = split(/\s+/,$reagents);

    $recipes->add(KoLBot::Recipe->new(products => [@products],
				      action   => $action,
				      reagents => [@reagents],
				      ));
  }
  close FILE;
}

END {} ;

1;

