#!/usr/bin/perl

# 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.  

# recipes.pl
# Makes recipe file from the web page
# http://www.agesoftime.com/kol/kol_list_mix.php
# doesn't include meat, meat stacks, use: wad of dough <=> flat dough
# 22 July 2004

use KoLBot::Items;
use KoLBot::Recipe;

my $ID = '$Id: recipes.pl 68 2004-11-29 00:56:29Z alan $';

if (@ARGV > 1) {
  print "usage: recipes.pl source.html\n\n";
  print "  Prints the resulting recipe database\n";
  print "  If source.html is omittied, recipes.html is assumed\n";
  print "  Expects a file in the current directory, items.txt with items\n";
  print "  You may wish to redirect the output to a suitable file\n";
}

my $ignore_unknown_items = 1;

# product, action, item1, item2

my $items = new KoLBot::Items(config => { file => 'items.txt'});
$items->init();
my @recipes;

my $in_file = $ARGV[0] || 'recipes.html';

open INF,"<",$in_file or die "Cannot open source file $in_file";
my $content;
while(<INF>) {
  $content = $_, last if m|^<tr>.*</tr>$|;
}
close INF;
$content =~ m|^<tr>(.*)</tr>$|;
$content = $1;

my @lines = split /<\/tr><tr>/,$content;

for (@lines) {
  # number in store and price come after this stuff
  # price also occurs in the \d{9} part.

  m{=\d+>(.+)</a>.*<td>(Mix|Combine|Smith|Cook).*=\d+>(.+)</a>.*=\d+>(.+)</a>.*=\d+>(.+)</a>};

  my $t = $1;
  my $act = $2;
  my $i1 = $3;
  my $i2 = $4;

  $t =~ s/\361/&ntilde;/g;
  $i1 =~ s/\361/&ntilde;/g;
  $i2 =~ s/\361/&ntilde;/g;
  $t =~ s/\231/&trade;/g;
  $i1 =~ s/\231/&trade;/g;
  $i2 =~ s/\231/&trade;/g;
  $t =~ s/caserole/casserole/g;
  $i1 =~ s/caserole/casserole/g;
  $i2 =~ s/caserole/casserole/g;

  if(!exists($items->by_name->{lc($t)})) {
    die "Item $t unknown" unless $ignore_unknown_items;
    warn "Item $t unknown";
    next;
  } 
  if(!exists($items->by_name->{lc($i1)})) {
    die "Item $i1 unknown" unless $ignore_unknown_items;
    warn "Item $i1 unknown";
    next;
  } 
  if(!exists($items->by_name->{lc($i2)})) {
    die "Item $i2 unknown" unless $ignore_unknown_items;
    warn "Item $i2 unknown";
    next;
  }

  push @recipes,new KoLBot::Recipe(product => $items->by_name->{lc($t)}->id,
				   action  => lc($act),
				   reagents => [$items->by_name->{lc($i1)}->id,
						$items->by_name->{lc($i2)}->id,
						],
				   );
}

for (@recipes) {
  print $_->products, " ",$space,$_->action, ' ', $_->reagents->[0],,
    ' ', $_->reagents->[1],"\n";
} 
