DROP FUNCTION get_work (mylocidispid BIGINT);
CREATE FUNCTION get_work (mylocidispid BIGINT) RETURNS TABLE (client_id VARCHAR(64)) ROWS 5 VOLATILE AS $$
BEGIN
	CREATE TEMPORARY TABLE foo (locidispid BIGINT, locid INT);
	INSERT INTO foo SELECT DISTINCT locidispid, locidispid/1000000 FROM connections where client_type = 'client';
	DELETE FROM foo WHERE locidispid IN (SELECT DISTINCT blocidispid FROM current_scores WHERE alocidispid = mylocidispid AND (current_timestamp - score_dt) < interval '24 hours');
	DELETE FROM foo WHERE locid NOT IN (SELECT locid FROM geoiplocations WHERE geog && st_buffer((SELECT geog from geoiplocations WHERE locid = mylocidispid/1000000), 806000));
	CREATE TEMPORARY TABLE bar (client_id VARCHAR(64), locidispid BIGINT, r DOUBLE PRECISION);
	INSERT INTO bar SELECT l.client_id, l.locidispid, random() FROM connections l, foo f WHERE l.locidispid = f.locidispid and l.client_type = 'client';
	DROP TABLE foo;
	DELETE FROM bar b WHERE r != (SELECT max(r) FROM bar b0 WHERE b0.locidispid = b.locidispid);
	RETURN QUERY SELECT b.client_id FROM bar b ORDER BY r LIMIT 5;
	DROP TABLE bar;
	RETURN;
END;
$$ LANGUAGE plpgsql;
