<?php
/*
* @package LabCMS
* @copyright (c) 2006 Alexander Levin aka Loki (loki_angel@mail.ru)
* @support http://labcms.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/

class adv_rotator_list extends ModuleTools
{
	public function __construct()
	{
		if (!$blocks=TCache::get('adv_blocks')) {
			$blocks=$this->getBlocks();
			TCache::set($blocks, 'adv_blocks');
		}
		
		if ($blocks) {
			foreach ($blocks as $id=>$block) {
				self::_assign('_module_ad_rotator_'.$id, $block);
			}
		}
	}
	
	public function getAllBlocks()
	{
		//TODO тут можно поднять из кэша
		$result=Db::i()->select(
			"SELECT p.place_id, value, rate, value_id
			FROM ?_ad_rotator_places p
			LEFT JOIN ?_ad_rotator_values v ON p.place_id=v.place_id
			WHERE p.active=1 AND v.active=1"
		);
		$places=array();
		if ($result) {
			foreach ($result as $var) {
				if ($var['rate']<1) continue;
				if (!isset($places[$var['place_id']]['max_rate'])) $places[$var['place_id']]['max_rate']=0;
				$places[$var['place_id']]['max_rate']+=$var['rate'];
				$places[$var['place_id']]['blocks'][]=array(
					'value'=>$var['value'],
					'rate'=>$places[$var['place_id']]['max_rate']
				);
			}
		}
		//TODO тут можно положить в кэш
		return $places;
	}
	
	public function getBlocks()
	{
		$places=$this->getAllBlocks();
		$result=array();
		if (count($places)) {
			foreach ($places as $place_id=>$data) {
				$rand=rand(1, $data['max_rate']);
				foreach ($data['blocks'] as $val) {
					if ($rand<=$val['rate']) {
						$result[$place_id]=$val['value'];
						break;
					}
				}
			}
		}
		return $result;
	}
}