#!/usr/bin/python
__author__ = 'dano'



import pygame
import pygame.camera
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import ThreadingMixIn
import re
import StringIO
import Image
import settings
import sys

refreshfile = open('refresher.html')
refreshstring = refreshfile.read()

refreshstring = re.sub(r'{{IPADDRESS}}',settings.host,refreshstring)
refreshstring = re.sub(r'{{PORT}}',str(settings.port),refreshstring)


print refreshstring
sys.exit()

pygame.init()
pygame.camera.init()

cam = pygame.camera.Camera(settings.DEVICE,settings.SIZE)
cam.start()


def bgserver(name):

	class MyHandler(BaseHTTPRequestHandler):
		def do_GET(self):
	
			#self.wfile.write("<hr>")
			#self.wfile.write("All Shows: ")
			#self.wfile.write("<br><br>")
			if self.path == "/live":
				self.send_response(200)
				self.send_header('Content-type','text/html')
				self.end_headers()
				self.wfile.write(refreshstring)

			else:
				self.send_response(200)
				self.send_header('Content-type','image/png')
				#self.send_header('Content-type','text/html')
				self.end_headers()

				###works###
				i = cam.get_image()
				i = cam.get_image()
				i = cam.get_image()
				p = Image.fromstring('RGB',settings.SIZE,pygame.image.tostring(i,'RGB',False))
				o = StringIO.StringIO()
				p.save(o,'png')
				self.wfile.write(o.getvalue())



	class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
		pass

	server = ThreadedHTTPServer((settings.host, settings.port), MyHandler)
	print "started webserver on port " + str(settings.port)
	server.serve_forever()

bgserver('name1')
