from opencv.cv import *
from opencv.highgui import *

EVENTS = ['CV_EVENT_MOUSEMOVE', 'CV_EVENT_LBUTTONDOWN', 'CV_EVENT_RBUTTONDOWN',  'CV_EVENT_MBUTTONDOWN',  'CV_EVENT_LBUTTONUP',  'CV_EVENT_RBUTTONUP', 'CV_EVENT_MBUTTONUP'  , 'CV_EVENT_LBUTTONDBLCLK','CV_EVENT_RBUTTONDBLCLK','CV_EVENT_MBUTTONDBLCLK']

framequeue = []
currentframe = 0
slitlocation = 0
totalframes = 320

capture = cvCreateCameraCapture(0)
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 240)
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 320)

#height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT)
#width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH)
height = 240
width = 320

#cvSetCaptureProperty(capture, CV_CAP_PROP_FPS, 5)
#print "Webcam at ", str(cvGetCaptureProperty(capture, CV_CAP_PROP_FPS)), "fps..."

frame = cvQueryFrame(capture)

for i in range(1, totalframes):
	tempframe = cvCreateMat(height, width, frame.type)
	framequeue.append(tempframe)

timeline = cvCreateMat(height, width, frame.type)
camera = cvCreateMat(height, width, frame.type)

def get_camera_frame():
	global capture
	global framequeue
	global currentframe
	currentframe = currentframe + 1
	if currentframe == totalframes - 1:
		currentframe = 0
	frame = cvQueryFrame(capture)
	cvCopy(frame, framequeue[currentframe])
	cvFlip(framequeue[currentframe])

def update_live_view():
	global camera
	global framequeue
	global currentframe
	global slitlocation
	cvCopy(framequeue[currentframe], camera)
	cvLine(camera, cvPoint(slitlocation, 0), cvPoint(slitlocation, camera.height), CV_RGB(255, 0, 0))
	cvShowImage("live", camera)

def update_timeline():
	global framequeue
	global currentframe
	global timeline
	global slitlocation
	drawslit = 0
#	for i in range(totalframes - 1):
#		timeline[:,drawslit] = framequeue[i][:,slitlocation]
#		drawslit = drawslit + 1
	partway = totalframes - currentframe
	for i in range(currentframe, totalframes - 1):
		timeline[:,drawslit] = framequeue[i][:,slitlocation]
		drawslit = drawslit + 1
	for i in range(0, currentframe - 1):
		timeline[:,drawslit] = framequeue[i][:,slitlocation]
		drawslit = drawslit + 1
	cvFlip(timeline)
	cvShowImage("timeline", timeline)

mousedown = False

def camera_mouse(event, x, y, flags, params):
	global mousedown
	global slitlocation
	if EVENTS[event] == 'CV_EVENT_LBUTTONDOWN':
		mousedown = True
	elif EVENTS[event] == 'CV_EVENT_LBUTTONUP':
		mousedown = False
	if mousedown == True and x > 0 and x < width and y > 0 and y < height:
		slitlocation = x

cvStartWindowThread()
cvNamedWindow("timeline")
cvNamedWindow("live")

cvSetMouseCallback("live", camera_mouse)

while True:
	cvCopy(frame, framequeue[currentframe])
	get_camera_frame()
	update_live_view()
	update_timeline()
	k = cvWaitKey(10)
	if k == 'x1b':
		break