# Use at your own risk.
# Represents first few hours of playing with python.

import threading
import cgi
import wsgiref.handlers
import os
import logging
import timeit

from google.appengine.api import urlfetch
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db

logging.getLogger().setLevel(logging.DEBUG)

# From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/366178
def primes(n): 
  if n==2: return [2]
  elif n<2: return []
  s=range(3,n+1,2)
  mroot = n ** 0.5
  half=(n+1)/2-1
  i=0
  m=3
  while m <= mroot:
    if s[i]:
      j=(m*m-3)/2
      s[j]=0
      while j<half:
        s[j]=0
        j+=m
    i=i+1
    m=2*i+3
  return [2]+[x for x in s if x]

ceiling1 = 1
ceiling2 = 1

class Prime1(webapp.RequestHandler):
  def get(self):
    global ceiling1
    ceiling1 *= 2
    data = ""
    data = primes(ceiling1)
    time = ""
    # t = timeit.Timer("data = primes(ceiling1)")
    # time = t.timeit()
    template_values = { 'ceiling': ceiling1, 'data': data, 'time': time }
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

class Prime2(webapp.RequestHandler):
  def get(self):
    global ceiling2
    ceiling2 *= 4
    data = ""
    data = primes(ceiling2)
    time = ""
    # t = timeit.Timer("data = primes(ceiling2)")
    # time = t.timeit()
    template_values = { 'ceiling': ceiling2, 'data': data, 'time': time }
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

class Prime3(webapp.RequestHandler):
  def get(self):
    ceiling = 524288
    data = ""
    data = primes(ceiling)
    time = ""
    # t = timeit.Timer("data = primes(ceiling)")
    # time = t.timeit()
    template_values = { 'ceiling': ceiling, 'data': data, 'time': time }
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

class SelfTest(webapp.RequestHandler):
  def get(self):
    for num in range(1,1000):
      url = "http://siegel.appspot.com/ceiling-of-2"
      result = urlfetch.fetch(url)
      template_values = { 'ceiling': "", 'data': "", 'time': "" }
      path = os.path.join(os.path.dirname(__file__), 'index.html')
      self.response.out.write(template.render(path, template_values))
      #if result.status_code == 200:
        #doSomethingWithResult(result.content)

### Threading test stuff...
# From: http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/1/
theVar = 1
class MyThread ( threading.Thread ):
   def run ( self ):
      global theVar
      logging.info('This is thread ' + str ( theVar ) + ' speaking.')
      logging.info('Hello and good bye.')
      theVar = theVar + 1

class ThreadTest(webapp.RequestHandler):
  def get(self):
    global theVar
    for x in xrange ( 20000 ):
       MyThread().start()
    template_values = { 'ceiling': "", 'data': theVar, 'time': "" }
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

class ThreadTest20(webapp.RequestHandler):
  def get(self):
    global theVar
    for x in xrange ( 20 ):
       MyThread().start()
    template_values = { 'ceiling': "", 'data': theVar, 'time': "" }
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))
### END

class MainPage(webapp.RequestHandler):
  def get(self):
    data = ""
    #data = primes(ceiling)
    ceiling = ""
    time = ""
    # t = timeit.Timer("data = primes(ceiling)")
    # time = t.timeit()
    template_values = { 'ceiling': ceiling, 'data': data, 'time': time }
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

def main():
  application = webapp.WSGIApplication( [('/', MainPage), ('/ceiling-of-2', Prime1), 
                                        ('/ceiling-of-4', Prime2), ('/ceiling-fixed', Prime3),
                                        ('/thread-test-20', ThreadTest20),
                                        ('/thread-test-20k', ThreadTest),
                                        ('/self-test', SelfTest)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()

