#!/usr/bin/python2.5

# Critter Caretaker
# A virtual pet to care for
# This is a further revised version of Michael Dawson's 
# critter_caretaker.py from chapter 8 of Michael Dawson, 
# "Python: Programming for the Absolute Beginner," 
# Third Edition, Course Technology PTR, 2010, 
# Cengage Learning, Boston, ISBN 978-1-4354-5500-9, 
# to run as a Python 2 cgi-bin script. 
# =================================================

import sys
import os
from cgi import escape

def getargs( qstring ):
    """Extract CGI arguments as a dictionary"""
    rvalue = {}
    ipos = 0
    prevpos = 0
    while ipos < len(qstring):
        if qstring[ipos] == '=':
            kval = qstring[prevpos:ipos]
            ipos = ipos+1
            prevpos = ipos
            while ipos < len(qstring):
                if qstring[ipos] == '&':
                    vval = qstring[prevpos:ipos]
                    ipos = ipos+1
                    prevpos = ipos
                    break
                ipos = ipos+1
                if ipos == len(qstring):
                    vval = qstring[prevpos:ipos]
                    break
            rvalue[kval] = vval
        else:
            ipos = ipos+1
            if ipos == len(qstring):
                rvalue["(nokey)"] = qstring[prevpos:ipos]
    return rvalue

class Critter(object):
    """A virtual pet"""
    def __init__(self, name, hunger = 0, boredom = 0):
        self.name = name
        self.hunger = hunger
        self.boredom = boredom

    def __pass_time(self):
        self.hunger += 1
        self.boredom += 1

    @property
    def mood(self):
        unhappiness = self.hunger + self.boredom
        if unhappiness < 5:
            m = "happy"
        elif 5 <= unhappiness <= 10:
            m = "okay"
        elif 11 <= unhappiness <= 15:
            m = "frustrated"
        else:
            m = "mad"
        return m
    
    def talk(self):
        print "I'm", self.name, "and I feel", self.mood, "now.\n"
        self.__pass_time()
        return (self.hunger,self.boredom)
    
    def eat(self, food = 4):
        print "Brruppp.  Thank you."
        self.hunger -= food
        if self.hunger < 0:
            self.hunger = 0
        self.__pass_time()
        return (self.hunger,self.boredom)

    def play(self, fun = 4):
        print "Wheee!"
        self.boredom -= fun
        if self.boredom < 0:
            self.boredom = 0
        self.__pass_time()
        return (self.hunger,self.boredom)

def GetCGIArg(myargs,argname):
    """ get a string arg """
    try:
        argstr = myargs[argname]
    except:
        argstr = ""
    return argstr
    
def GetCGIIntArg(myargs,argname):
    """ get an integer arg """
    try:
        argstr = myargs[argname]
    except:
        argstr = "0"
    return int(argstr)
    
def SetCGIArg(myargs,argname,argval):
    """ update the argument in the dictionary """
    oldval = GetCGIArg(myargs,argname)
    myargs[argname] = argval
    return oldval

def PutCGIArg(myargs,argname):
    """ put the argument out as a hidden arg"""
    print "<input type=hidden  name=\""+argname+"\" " \
        +"value=\""+str(GetCGIArg(myargs,argname))+"\" /><br />"


def main():
    print "Content-type: text/html"
    print
    print "<html>"
    print "<head>"
    print "<title>"+escape("Critter Caretaker")+"</title>"
    print "</head>"
    print "<body>"
    keys = os.environ.keys()
    myargs=getargs(os.environ["QUERY_STRING"])
    crit_name = GetCGIArg(myargs,"crit_name")
    hunger = GetCGIIntArg(myargs,"hunger")
    boredom = GetCGIIntArg(myargs,"boredom")
    restart = GetCGIIntArg(myargs,"restart")
    crit = Critter(crit_name,hunger,boredom)
    print "\n<h2 align=center>Critter Caretaker</h2>"
    print "<form action="\
    "http://arcib.dowling.edu/cgi-bin/cgiwrap/bernsteh/critter_caretaker_3.py" + \
    " method=\"GET\">"
    print "\n<p><pre><tt>"
    print \
        """
        Critter Caretaker
        """
    choice = GetCGIIntArg(myargs,"choice")
    # exit
    if choice == int("0"):
        if restart == int("0"):
            SetCGIArg(myargs,"restart","1")
            restart = 1
            print "What would you like to do with your critter "+crit_name
            print \
            """
            0 - Quit
            1 - Listen to your critter
            2 - Feed your critter
            3 - Play with your critter
            """
        else:
            print "Good-bye."
            SetCGIArg(myargs,"crit_name","")
            crit_name = ""
            SetCGIArg(myargs,"restart","0")
            restart = 0
        SetCGIArg(myargs,"boredom","0")
        SetCGIArg(myargs,"hunger","0")
    else:
        SetCGIArg(myargs,"restart","1")
        restart = 1

        # listen to your critter
        if choice == int("1"):
            (hunger,boredom)=crit.talk()
        
        # feed your critter
        elif choice == int("2"):
            (hunger,boredom)=crit.eat()
         
        # play with your critter
        elif choice == int("3"):
            (hunger,boredom)=crit.play()

        # some unknown choice
        else:
            print "\nSorry, but", choice, "isn't a valid choice."
            
        print "What would you like to do with your critter "+crit_name
        print \
        """
        0 - Quit
        1 - Listen to your critter
        2 - Feed your critter
        3 - Play with your critter
        """
    SetCGIArg(myargs,"hunger",hunger)
    SetCGIArg(myargs,"boredom",boredom)
    if restart != int("0") or choice != int("0"):
        print "Choice: <input type=text name=\"choice\" "+\
            " value=\""+str(choice)+"\" /><br />"
        print "  Name: <input type=text name=\"crit_name\""+\
            " value=\""+crit_name+"\" /><br />"
    PutCGIArg(myargs,"hunger")
    PutCGIArg(myargs,"boredom")
    PutCGIArg(myargs,"restart")
    if restart == int("0"):
        print "<input type=\"submit\" value=\"try again\">"
    else:
        print "<input type=\"submit\" value=\"submit choice\">"
    print "\n</tt></pre>"
    print "\n</body>"
    print "\n</html>"

main()