#!/usr/bin/python

# shotCGI.py -- Simple shotput simulation CGI program using cgiAPP
#    Note: This is not yet production quality, as it uses default error
#          handling supplied by cgiApp


import cgiApp

stylesheet = """\
body {background-color: lightblue}
h1 {text-align: Center}
table {border-style: grooved; border-width: 2; width: 50%; margin-left: 25%}
th {text-align: Right; background-color: lightgray}
td {text-align: Right; background-color: white}
"""

table_headings = """\
<tr>
    <th>Time</th>
        <th>Height</th>
           <th>Distance</td>
</tr>
"""

datafmt = """\
<tr>
    <td>%0.2f</td>
       <td>%0.2f</td>
          <td>%0.2f</td>
</tr>
"""


class ShotCGI(cgiApp.CGIApp):

    LENGTH_LIMIT = 500

    DATA_TIMEOUT = 3

    REQ_FIELDS = ['angle', 'velocity', 'height']

    OPT_FIELDS = [('duration','10'), ('interval','0.5')]

    def ProcessRequest(self, form):
        # Perform the simulation
        try:
            shot = Shotput(float(form['angle']),
                           float(form['velocity']),
                           float(form['height']))
            dur = float(form['duration'])
            interval = float(form['interval'])
        except:
            cgiApp.send_error("Misformatted Data",
                              "Some of the values you typed weren't numbers")
            raise cgiApp.CGIQuit()
        t = 0
        data = []
        while t <= dur:
            data.append((t, shot.height(t), shot.distance(t)))
            t = t + interval
        self.__data = data

    def GetTitle(self):
        return "Shotput Simulaton Results"

    def GetStylesheet(self):
        return stylesheet

    def GetBody(self):
        lines = []
        lines.append("<h1> Shotput Simulation Results</h1>")
        lines.append("<hr />")
        lines.append('<table border="border">')
        lines.append(table_headings)
        rows = self.__data
        for row in rows:
            lines.append(datafmt % row)
        lines.append("</table>")
        return "\n".join(lines)

class Shotput:

    def __init__(self, angle, vel, h0):
        from math import sin, cos, pi
        theta = self.angle = angle * pi / 180.0
        self.xvel = vel * cos(theta)
        self.yvel = vel * sin(theta)
        self.h0 = h0

    def height(self, t):
        return -4.9 * t * t + t*self.yvel + self.h0

    def distance(self, t):
        return t * self.xvel

if __name__ == "__main__":
    ShotCGI().run()



