#JES has its own sqrt, but without it we have to import it 
from math import sqrt, fmod
import time

def getCopy(pic):
	"""Return an exact copy of the picture passed as parameter.
	Included since duplicatePicture(pic) is only available in JES 3.1"""
	
	h = getHeight(pic)
	w = getWidth(pic)
	newPic = makeEmptyPicture(w,h)
  
	for x in range(1, w+1):
		for y in range(1, h+1):
			newP = getPixel(newPic,x,y)
			p = getPixel(pic,x,y)
			setColor(newP, getColor(p))
	
	return newPic
	
def scale(pic, width, height):
	"""Scales picture pic to the "width" and "height"
	dimensions and returns the result"""
	
	facX = (1.0 * width) / getWidth(pic)
	facY = (1.0 * height) / getHeight(pic)
	stepX = 1 / facX
	stepY = 1 / facY
	canvas = makeEmptyPicture(width, height)

	# Now, do the actual copying
	sourceX = 1
	for targetX in range(1,width + 1):
		sourceY = 1
		for targetY in range(1,height + 1):
			color = getColor(getPixel(pic, int(sourceX), int(sourceY)))
			setColor(getPixel(canvas, targetX, targetY), color)
			sourceY = sourceY + stepY
		#incrementing column number
		sourceX = sourceX + stepX
	return canvas

def jointShapeCircle(canvas, pic1, pic2, frac):
	"""Display the two pictures pic1 and pic2
	on the same canvas, with outer portion is "radius-frac"
	occupied by pic2 and inner part with pic1"""
	
	w1 = pic1.getWidth()
	h1 = pic1.getHeight()
	w2 = pic2.getWidth()
	h2 = pic2.getHeight()
	assert (h1 == h2 and w1 == w2), "Pictures have different dimensions!"
	
	assert (0 <= frac <= 1), "The frac must be that -- 'fraction'!"
	
	h = canvas.getHeight()
	w = canvas.getWidth()
	R = sqrt((0.5 * h)**2 + (0.5 * w)**2)
	
	r = R * frac
	
	# centre of the picture
	x0 = w / 2
	y0 = h / 2
	
	for y in range(1, h + 1):
		for x in range(1, w + 1):
			canP = getPixel(canvas,x,y)
			p1 = getPixel(pic1,x,y)
			p2 = getPixel(pic2,x,y)
			if dist(x,y,x0,y0) < r:
				setColor(canP, getColor(p2))
			else:
				setColor(canP, getColor(p1))
				
def dist(x1, y1, x2, y2):
  return sqrt((x1 - x2)**2 + (y1 - y2)**2)
 

def shapeCircleSlide(pic1, pic2, numSteps):
	h1 = pic1.getHeight()
	h2 = pic2.getHeight()
	w1 = pic1.getWidth()
	w2 = pic2.getWidth()
	assert (h1 == h2 and w1 == w2), "The pictures must have the same dimensions."
	
	copy = getCopy(pic1)
	
	delta = 1.0 / numSteps
	jointShapeCircle(copy,pic1,pic2,0)
	copy.show()
	
	start = time.time()
	#steps = range(1, numSteps + 1)
	#tlist = map(lambda a: 1.0*a/numSteps,steps)
	for i in range(1, numSteps + 1):
		jointShapeCircle(copy,pic1,pic2,float(i)/numSteps)
		copy.repaint()

	finish = time.time()
	print "The transition time is %d seconds" %(finish - start)

