<?php
class ExcerptController extends Controller
{

   public function actionRandom($excerptCode = null) {
		$data = array();

		do {
			$excerpt = null;
			if ($excerptCode !== null) {
				$excerpt = ExcerptRecord::model()->find(array(
					'select'=> 'code, hash, text',
					'condition' => 'code = :code',
					'params' => array('code' => $excerptCode)
				));
			}

			if ($excerpt === null) {
				$excerpt = ExcerptRecord::model()->find(array(
					'select'=> 'code, hash, text, rand() + hits as rand',
					'condition' => 'enabled = 1',
					'limit'=> 1,
					'order'=> 'rand',
				));
			}

//SELECT e.code, COALESCE( hitter.hits, 0 ) + rand( ) rand
//FROM keystats_excerpt e
//LEFT JOIN (
//
//	SELECT r.excerptcode, count( 1 ) hits
//	FROM keystats_run r
//	WHERE volunteercode
//	IN (
//
//		SELECT v.code
//		FROM keystats_volunteer v
//		JOIN keystats_source s ON s.code = v.sourcecode
//		WHERE s.tag = 'DEVEL'
//	)
//GROUP BY excerptcode
//) hitter ON hitter.excerptcode = e.code
//ORDER BY rand DESC
//LIMIT 1

			if ($excerpt === null) {
				Yii::log('Excerpt not found', CLogger::LEVEL_ERROR);
				break;
			}
		// skip paragraphs that contain symbols not on the keyboard
		} while (preg_match('/[^0-9a-zA-ZõäöüšžÕÄÖÜŠŽ,;.:\?\!"\'\s\-\(\)\[\]\/%&@€£\$=\+\*<>]/u', $excerpt->text) == true);

		if ($excerpt) {
			$data = array(
				'hash' => $excerpt->hash,
				'text' => $excerpt->text
			);
		}
		$this->renderPartial('random', array('data' => $data));
   }

}
