// ==PREPROCESSOR==
// @name "LoadImageAsync"
// @author "T.P Wang"
// ==/PREPROCESSOR==

// Get a list of jpg files from a folder
var g_image_list = utils.Glob("c:\\windows\\web\\wallpaper\\*.jpg").toArray();
var ww = 0, wh = 0;
var g_img = null;
var g_valid_tid = 0;

// Trigger every 5 seconds.
var g_timer = window.SetInterval(function () {
	load_random_image_async();
}, 5000);

load_random_image_async();

function load_random_image_async() {
	// Load a random image from the list
	var path = g_image_list[Math.floor(Math.random() * g_image_list.length)];
	// on_load_image_done will be triggered when the image has been loaded
	g_valid_tid = gdi.LoadImageAsync(window.ID, path);
}

function on_size() {
	ww = window.Width;
	wh = window.Height;
}

function on_paint(gr) {
	if (g_img) {
		// Keep aspect ratio
		var scale_w = ww / g_img.Width;
		var scale_h = wh / g_img.Height;
		var scale = Math.min(scale_w, scale_h);
		var pos_x = 0, pos_y = 0;
		if (scale_w < scale_h)
			pos_y = (wh - g_img.height * scale) / 2;
		else if (scale_w > scale_h)
			pos_x = (ww - g_img.Width * scale) / 2;
		gr.DrawImage(g_img, pos_x, pos_y, g_img.Width * scale, g_img.Height * scale, 0, 0, g_img.Width, g_img.Height);
	}
}

// After loading image is done in the background, this callback will be invoked
function on_load_image_done(tid, image) {
	if (g_valid_tid == tid) {
		if (g_img)
			g_img.Dispose();
		g_img = image;
		window.Repaint();
	}
}
