<?php

$mod->setDefaultCV("randommapcycle", "enabled", 0);
$mod->setDefaultCV("randommapcycle", "maps", $mod->getMaps(","));
$mod->setDefaultCV("randommapcycle", "gametypes", $mod->getCurrentGametype());
$mod->setDefaultCV("randommapcycle", "notlastmaps", 3);
$mod->setDefaultCV("randommapcycle", "notlastgt", 1);

$mod->registerEvent("nextMap", "randommapcycle_set");

randommapcycle_set();

function randommapcycle_set() {
	global $mod;
	global $logging;
	global $randommapcycle_maps;

	if (!$mod->getCV("randommapcycle", "enabled")) {
		return false;
	}

	if ($mod->getCV("randommapcycle", "notlastmaps") < 1) {
		$logging->write(MOD_WARNING, "Randommapcycle: ConfigVar [randommapcycle]notlastmaps must be greater than 0, randommapcycle will be disabled");
		return false;
	}

	$lastmaps = $mod->getLastMaps(2);
	$maps = explode(",", $mod->getCV("randommapcycle", "maps"));
	$gametypes = explode(",", $mod->getCV("randommapcycle", "gametypes"));

	if ($lastmaps[1] != $lastmaps[0]) {
		$randommapcycle_maps[] = $lastmaps[0];
		while (count($randommapcycle_maps) > $mod->getCV("randommapcycle", "notlastmaps")) {
			array_shift($randommapcycle_maps);
		}

		foreach ($maps as $key => $value) {
			if (in_array($value, $randommapcycle_maps)) {
				unset($maps[$key]);
			}
		}

		if (empty($maps)) {
			$logging->write(MOD_WARNING, "Randommapcycle: Can't choose a random map because count(\$maps) = 0");
			return false;
		}

		$maps = array_merge($maps);

		if ($mod->getCV("randommapcycle", "notlastgt")) {
			foreach ($gametypes as $key => $value) {
				if ($value == $mod->getCurrentGametype()) {
					unset($gametypes[$key]);
				}
			}

			$gametypes = array_merge($gametypes);
		}

		if (empty($gametypes)) {
			//$logging->write(MOD_WARNING, "Randommapcycle: Can't choose a gametype because count(\$gametypes) = 0, choosing current: ".$mod->getCurrentGametype());
			$gametypes[] = $mod->getCurrentGametype();
		}

		$randommap = $maps[rand(0, count($maps) - 1)];
		$randomgt = $gametypes[rand(0, count($gametypes) - 1)];

		$logging->write(MOD_NOTICE, "Randommapcycle: Setting nextmap to $randommap ($randomgt)");
		$mod->rconSetNextMap($randommap, $randomgt, false);
	}

	return true;

}

?>