#!/usr/local/bin/perl
################################################################################
#                                                                              #
# BASIC.PL                                                                     #
#                                                                              #
# Just the shell of a CGI script, with no guts yet.                            #
#                                                                              #
################################################################################
### SERVER SPECIFIC PARAMETERS #################################################
################################################################################

$dfile = "data.txt";
$debugmode = 0;
$debug = "<H3>DEBUG DATA</H3>";




################################################################################
### PARSE USER INPUT ###########################################################
################################################################################

if($ENV{'CONTENT_LENGTH'}){
  read(STDIN, $in, $ENV{'CONTENT_LENGTH'});
  }else{
  $in = $ENV{'QUERY_STRING'};
  }

$debug .= "<TABLE BORDER>";
@in = split(/[&;]/,$in);
foreach $i (0 .. $#in) {
   $in[$i] =~ s/\+/ /g;
   ($key, $val) = split(/=/,$in[$i],2);
   $key =~ s/%([A-Fa-f0-9]{2})/pack("c",hex($1))/ge;
   $val =~ s/%([A-Fa-f0-9]{2})/pack("c",hex($1))/ge;
   $in{$key} .= "\0" if (defined($in{$key}));
   $in{$key} .= $val; 
   $debug .= "<TR><TD>$key</TD><TD>$val</TD></TR>";
   }
$debug .= "</TABLE>";


################################################################################
### FUNCTION SPLITTER ##########################################################
################################################################################

# set ds = 1 if a serch is run

$ds = 0;
$ds = 1 if ( $in{'s'} );
$ds = 0 unless ( $in{'t'} || $in{'c'} || $in{'i'} );
$debug .= "ds = $ds<BR>";



# read the data ...

open (DF, "$dfile") || &scriptError(2);
while (<DF>){
  chomp($_);
  @f = split(/\t/,$_);
  # create arrays for select objects
  $allt{$f[2]}++;
  $allt{$f[3]}++;
  $allc{$f[4]}++;
  $allc{$f[5]}++;
  $allc{$f[6]}++;
  $alli{$f[7]}++;
  $alli{$f[8]}++;
  $alli{$f[9]}++;
  $allcount++;
  next unless ($ds);
  # here, try to match search criteria 
  if ($in{'t'}){
     next unless ( ($in{'t'} eq $f[2]) || ($in{'t'} eq $f[3]) );
     }
  if ($in{'c'}){
     next unless ( ($in{'c'} eq $f[4]) || ($in{'c'} eq $f[5])  || ($in{'c'} eq $f[6]));
     }
  if ($in{'i'}){
     next unless ( ($in{'i'} eq $f[7]) || ($in{'i'} eq $f[8])  || ($in{'i'} eq $f[9]));
     }
  $dl = "<A HREF=\"";
  if ($f[10]){
     $dl .= "http://$f[10]";
     }else{
     $st = $f[1]; $st =~ s/\s+/+/g; $st = "recipe $st";
     $dl .= "http://www.google.com/search?q=$st";
     }
  $dl .= "\" TARGET=\"_new\">$f[1]</A>";
  $dl .= " [$f[0]]" if ($debugmode);
  $match{$dl} = 1;
  }


# $f[0] => unique ID
# $f[1] => Name
# $f[2] => Type 1
# $f[3] => Type 2
# $f[4] => Cuisine 1
# $f[5] => Cuisine 2
# $f[6] => Cuisine 3
# $f[7] => Ingredient 1
# $f[8] => Ingredient 2
# $f[9] => Ingredient 3
# $f[10] => Link (optional)

## 





close (DF);



#### when seraching
# create a hash with a key of some HTML code to render the line
# set value +1 for each criteria matched
# sort results array randomly
# resurt by match value
# barf top matches (up to five)








# if any search criteria is received, render search results

 if ($in{'s'} && $ds){ 
    $o .= "<H1>Search Results</H1>"; 
    @matches = keys %match;
    $debug .= @matches . " matches<BR>";
    if (@matches){
       @matches = sort { (-1,0,1)[rand 3] } @matches;
       $o .= "<UL>";
       $c = 0;
       foreach $m (@matches){
          $o .= "<LI> $m</LI>";
          $c++;
          last if ($c == 5);
          }
       $o .= "</UL>";
       }else{
       $o .= "<P>Nothing found.</P>";
       }
    }elsif($in{'s'}){
    $o .= "<H1>Search Results</H1>"; 
    $o .= "<P>No search terms were entered.</P>\n\n";
    }else{
    $o .= "<H1>What to Cook?</H1>";
    $o .= "<P>A little help for days when I'm feeling uninspired ... enter ";
    $o .= "one or more of the criteria to pull up five random dishes from ";
    $o .= "a database of $allcount items.  (Yes, it used to be more, but I borked ";
    $o .= "the data file.)</P>\n\n";
    }







# TODO - barf search results


# if no search criteria are received, just render the form
# render the form even if a search has been done, to allow a new search

# the user provided no criteria if $in{'s'} is passed but $ds is zero value




 if ($in{'s'}){ $o .= "<H2>Search Again</H2>"; }
    


$o .= "<FORM METHOD=\"POST\" ACTION=\"wtc.jsp\">";
$o .= "<INPUT TYPE=\"hidden\" NAME=\"s\" VALUE=\"1\">";
$o .= "<TABLE>";
$o .= "<TR><TD CLASS=\"label\">Type</TD><TD><SELECT NAME=\"t\">";
$o .= "<option value=\"\">- Select -</option>";

foreach (sort {$a cmp $b} keys (%allt)){
   next unless ($_);
   $o .= "<option>$_</option>";
   }

$o .= "</SELECT></TD></TR>";
$o .= "<TR><TD CLASS=\"label\">Cuisine</TD><TD><SELECT NAME=\"c\">";
$o .= "<option value=\"\">- Select -</option>";

foreach (sort {$a cmp $b} keys (%allc)){
   next unless ($_);
   $o .= "<option>$_</option>";
   }

$o .= "</SELECT></TD></TR>";
$o .= "<TR><TD CLASS=\"label\">Ingredient</TD><TD><SELECT NAME=\"i\">";
$o .= "<option value=\"\">- Select -</option>";

foreach (sort {$a cmp $b} keys (%alli)){
   next unless ($_);
   $o .= "<option>$_</option>";
   }

$o .= "</SELECT></TD></TR>";
$o .= "<TR><TD></TD><TD><INPUT TYPE=\"submit\" VALUE=\"Search\"></TD></TR>";
$o .= "</TABLE></FORM>";





$o .= "";
$o .= "";
$o .= "";
$o .= "";
$o .= "";
$o .= "";
$o .= "";
$o .= "";
$o .= "";
$o .= "";
$o .= "";
$o .= "";
$o .= "";
$o .= "";
$o .= "";








# TODO - barf search results






# $in{'t'} => Dish Type
# $in{'c'} => Cuisine
# $in{'i'} => Ingredient


&display($o);

################################################################################
### FUNCTIONS ##################################################################
################################################################################








################################################################################
################################################################################
################################################################################
### INWORK BELOW


### INWORK ABOVE
################################################################################
################################################################################
################################################################################



################################################################################
### SUBROUTINE: FATAL ERROR MESSAGES ###########################################
################################################################################

sub scriptError{
  $o = "<H1>Error Type $_[0]</H1>\n\n<P>";
  $o .= "EOF error - no data returned" if ($_[0] eq '1');
  $o .= "Unable to read data file" if ($_[0] eq '2');
  $o .= "" if ($_[0] eq '3');
  $o .= "" if ($_[0] eq '4');
  $o .= "" if ($_[0] eq '5');
  $o .= "" if ($_[0] eq '6');
  $o .= "" if ($_[0] eq '7');
  $o .= "" if ($_[0] eq '8');
  $o .= "" if ($_[0] eq '9');
  $o .= "" if ($_[0] eq '10');
  $o .= "</P>\n\n";
  &display($o,"System Error");
  }

################################################################################
### SUBROUTINE: PRINT TO SCREEN ################################################
################################################################################

sub display{
  print "Content-type: text/html\n\n";
  $switch = 0;
  open (TMP,"wtc.tmp");
  while (<TMP>){
    chomp ($_);
    if ($_ eq '<!-- HERE -->'){
        print $_[0];
        }else{
        print "$_\n";
        }
     }
  close(TMP);
  print "<HR>$debug" if ($debugmode); 
  exit;
  }



################################################################################
######################################################################### EOF ##
&scriptError(1); ###############################################################

