#!/usr/bin/env ascript
import(sdl)
import(gif)
import(jpeg)

I(filename:string) = path.join(sys.datadir, 'sample', 'resource', filename)
sdl.Init(sdl.INIT_EVERYTHING)
[wdScreen, htScreen] = [1024, 768]
screen = sdl.SetVideoMode(wdScreen, htScreen, 16, sdl.SWSURFACE)
wdImage = 200
imageBg = image(I('Winter.jpg'), `rgb).resize(wdScreen, htScreen)
imagesL = gif.read(I('chicken-anim.gif'), `rgba).images::resize(wdImage)
imagesR = imagesL::flip(`horz)
xStep = wdImage / 10

Chicken = class {
	__init__(x:number, y:number, dir:symbol) = {
		[self.x, self.y] = [x, y]
		self.turnTo(dir)
	}
	turnTo(dir:symbol) = {
		if (dir == `right) {
			self.xDir = xStep
			self.imageIter = imagesR.round()
		} else {
			self.xDir = -xStep
			self.imageIter = imagesL.round()
		}
	}
	doAction() = {
		image = self.imageIter.next()
		screen.PutSurface(image, self.x, self.y - image.height)
		self.x += self.xDir
		if (self.x + wdImage > wdScreen) {
			self.turnTo(`left)
		}
		if (self.x < 0) {
			self.turnTo(`right)
		}
	}
}
chickens = repeat(3):list {
	x = rand(wdScreen - wdImage)
	y = rand(htScreen - wdImage) + wdImage
	dir = chooseif(rand() < .5, `left, `right)
	Chicken(x, y, dir)
}
//font = sdl.OpenFont(path.join(os.getenv("SystemRoot"), "Fonts", "arial.ttf"), 32)
sdl.AddTimer(100) {
	screen.PutSurface(imageBg, 0, 0)
	text = 'Chickens: %d' % chickens.len()
	//font.RenderText_Blended(text, color(`white)) {|surface|
	//	screen.PutSurface(surface, 10, 10)
	//}
	chickens::doAction()
	screen.UpdateRect()
	true
}
repeat {
	event = sdl.WaitEvent()
	if (event.type == sdl.QUIT || \
				(event.type == sdl.KEYDOWN && event.sym == sdl.K_ESCAPE)) {
		break
	} elsif (event.type == sdl.MOUSEBUTTONDOWN) {
		dir = choose(event.button, `left, `left, `right, `right)
		chickens.add(Chicken(event.x, event.y, dir))
	}
}
