#!/usr/local/bin/perl

#
# Install (a modified version of) this program in your webserver's cgi-bin 
# directory.
#
# This demo program handles a request to return inventory information for
# .catalog=&.id=_fake_yahoo_item_&.code=_fake_yahoo_code_
# It returns the item availability information as its response.
#

require 5.001;
use strict;

if ($ENV{'REQUEST_METHOD'} ne "POST") {
    die("Expecting a POST, bailing");
}

my $o;
read(STDIN,$o,$ENV{'CONTENT_LENGTH'});

my %o;
for (split(/&/,$o)) {
    $_ =~ s/\+/ /g;
    my($key,$val) = split(/=/,$_,2);
    for ($key,$val) {
        $_ =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/ge;
    }
    $o{$key} = $val;
}

sub YahooFakeItem {
    my($info)=@_;
    my $itemid=$info->{".id"};


    if (defined $itemid && $itemid eq "_fake_yahoo_item_") {
        return 1;
    } else {
        return 0;
    }
}

sub GetItemAvailability {
    my($info)=@_;

    my $catalog=$info->{".catalog"};
    my $code=$info->{".code"};

    #
    # Replace this with your code to determine whether an item is in stock.
    # Return -1, if the item is unknown
    #        available quantity, if the item is valid.
    #
    srand;
    return int(rand(100));
}
my($avail);

if (YahooFakeItem(\%o)) {
    $avail="-1";
} else {
    $avail=GetItemAvailability(\%o);
}
print "Status: 200\n";
print "Content-Type: text/plain\n";
print "Available: $avail\n";


if ($avail <= 0) {
 print "Inventory-Message: The item is not currently available. Please check back later.\n";
   }

print "\n";