require "theme"
require "timer"
require "sprite"

declare {
   background = sprite.new("themes/" .. theme.name():sub(2) .. "/bg.png"),
   bg = sprite.new(theme.scr.w(), theme.scr.h()),
   snowflake1 = sprite.new(9, 9),
   snowflake2 = sprite.new(5, 5),
   snowflake3 = sprite.new(3, 3),
   snowflakes = {},
}

function make_snowflakes()
   local n, s1, s2, s3
   s1 = pixels.new(9, 9)
   s2 = pixels.new(5, 5)
   s3 = pixels.new(3, 3)
   s1:fill_circle(5, 5, 5, 255, 255, 255, 96);
   s2:fill_circle(2, 2, 3, 255, 255, 255, 96);
   s3:fill_circle(1, 1, 2, 255, 255, 255, 96);
   s1:copy_spr(snowflake1, 0, 0)
   s2:copy_spr(snowflake2, 0, 0)
   s3:copy_spr(snowflake3, 0, 0)
   for n = 1, 100 do
	  table.insert(snowflakes, {rnd(3), rnd(theme.scr.w()), rnd(theme.scr.h())})
   end
end

function draw_background()
   background:copy(0, 0, theme.scr.w(), theme.scr.h(), bg, 0, 0)
   if prefs.animation then
	  for i, snowflake in ipairs(snowflakes) do
		 if snowflake[1] == 1 then
			snowflake1:draw(bg, snowflake[2], snowflake[3])
			snowflake[2] = snowflake[2] + (rnd(4) - 2)
			snowflake[3] = snowflake[3] + 5
		 elseif snowflake[1] == 2 then
			snowflake2:draw(bg, snowflake[2], snowflake[3])
			snowflake[2] = snowflake[2] + (rnd(4) - 2)
			snowflake[3] = snowflake[3] + 4
		 else
			snowflake3:draw(bg, snowflake[2], snowflake[3])
			snowflake[2] = snowflake[2] + (rnd(4) - 2)
			snowflake[3] = snowflake[3] + 2
		 end
		 if snowflake[2] > theme.scr.w() or snowflake[3] > theme.scr.h() then
			snowflakes[i][1] = rnd(3)
			snowflakes[i][2] = rnd(theme.scr.w())
			snowflakes[i][3] = 0
		 end
	  end
   end
   bg:copy(0, 0, theme.scr.w(), theme.scr.h(), sprite.scr(), 0, 0)
end

function game.timer()
   draw_background()
   return false
end

function init()
   instead.fading_value = false
   instead.wait_use(false)
end

function start()
   make_snowflakes()
   if prefs.animation then
	  timer:set(75)
   end
end
