<?php

/**
 * Description of Keywizard
 *
 * @author ain
 */
class KeyWizardController extends Controller {

	protected $stepData;

	public function filters() {
		return array(
			'preLogin',
			'accessControl'
		);
	}

	public function accessRules() {
		return array(
			array('allow',
				'users' => array('@')),
			array('deny',
				'users' => array('*'))
		);
	}

	public function behaviors() {

		return array(
			'wizard' => array(
				'class' => 'application.components.WizardBehavior',
				'steps' => array(
					'Samm 1' => 'Introduction',
					'Samm 2' => 'Volunteer',
					'Samm 3' => 'Challenge',
					'Samm 4' => 'KeyReader',
					'Kokkuvõte' => 'Summary'),
				'autoAdvance' => false,
				'forwardOnly' => true,
				'finishedUrl' => Yii::app()->homeUrl,
				'events' => array(
					'onStart' => 'wizardStart',
					'onProcessStep' => 'keyWizardProcessStep',
					'onFinished' => 'wizardFinished',
					'onInvalidStep' => 'wizardInvalidStep',
					'onSaveDraft' => 'wizardSaveDraft'
				)
			)
		);
	}

	public function filterPreLogin($filterChain) {
		$source = Yii::app()->request->getParam('source');
		if ($source) {
			Yii::app()->user->loginUrl = array('site/login', 'source' => $source);
		}

		$filterChain->run();
	}

	public function actionIndex($step = null) {
		$this->process($step);
	}

	protected function randomString($length) {
		 $key = '';
		 $keys = array_merge(range(0, 9), range('a', 'z'));

		 for ($i = 0; $i < $length; $i++) {
			  $key .= $keys[array_rand($keys)];
		 }

		 return $key;
	}

	protected function generateVolunteerHash() {
		do {
			$newHash = $this->randomString(32);


		} while (VolunteerRecord::model()->findByAttributes(array('hash' => $newHash)));
		return $newHash;
	}

	protected function enter() {

		$challenge = new Challenge('manual');
	   $challenge->attributes = $this->read('Challenge');
		if (!$challenge->validate()) {
			$challenge->duration = null;
		}

		$sourceTag = Yii::app()->user->getName();
		$sourceRecord = SourceRecord::model()->findByAttributes(array(
			'tag' => $sourceTag,
		));
		$sourceCode = $sourceRecord->code;
		$volunteer = $this->read('Volunteer');

		$volunteerHash = $this->generateVolunteerHash();
		$volunteerRecord = new VolunteerRecord;
		$volunteerRecord->sourcecode = $sourceCode;
		$volunteerRecord->hash = $volunteerHash;
		$volunteerRecord->attributes = $volunteer;
		$volunteerRecord->duration = $challenge->duration;
		$volunteerRecord->useragent =  Yii::app()->request->userAgent;
		$volunteerRecord->ip = Yii::app()->request->userHostAddress;
		$volunteerRecord->referrer = Yii::app()->session['urlReferrer'];

		$running = $this->read('KeyReader');
		$runData = json_decode($running['runData'], true);
		if ($runData == null) {
			Yii::log('Could not parse json data: ' . '(' . json_last_error() . ')', CLogger::LEVEL_ERROR );
			$runData = array();
		}

		$runCount = 0;
		foreach ($runData as &$run) {
			$excerptRecord = ExcerptRecord::model()->findByAttributes(array('hash' => $run['hash']));
			if (!$excerptRecord) continue;
			$run['excerptCode'] = $excerptRecord->code;
			$runCount++;
		}

		if ($runCount > 0) {
			try {
				$transaction = $volunteerRecord->dbConnection->beginTransaction();

				if (!$volunteerRecord->save()) {
					throw new Exception('Vounteer not saved '
						 . print_r($volunteerRecord->getErrors(), true));
				}

				foreach ($runData as $runner) {
					if (!isset($runner['excerptCode'])) continue;
					$runRecord = new RunRecord();
					$runRecord->volunteercode = $volunteerRecord->code;
					$runRecord->excerptcode = $runner['excerptCode'];
					$runRecord->data = json_encode($runner['data']);
					$runRecord->createdate = date('Y-m-d H:i:s');

					if (!$runRecord->save()) {
						throw new Exception('Run not saved '
							 . print_r($runRecord->getErrors(), true));
					}

					if ($volunteerRecord->useten ) {
						$excerptRecord->updateCounters(
							 array('hits' => 1),
							 'code = :code',
							 array(':code' => $runner['excerptCode'])
						);
					}
				}
				$transaction->commit();

			} catch (Exception $e) {
				$transaction->rollback();
				Yii::log($e->getMessage(), CLogger::LEVEL_ERROR);
			}
		}

		return $volunteerHash;

	}

	public function actionEnterTypeResult() {

		$typeResultRecord = new TypeResultRecord();
		if (isset($_POST['TypeResult'])) {
			$volunteerRecord = VolunteerRecord::model()->findByAttributes(array(
				'hash' => $_POST['TypeResult']['volunteerhash']));
			if ($volunteerRecord && TypeResultRecord::model()->countByAttributes(array('volunteercode' => $volunteerRecord->code)) < 1) {
				$typeResultRecord->attributes = $_POST['TypeResult'];
				$typeResultRecord->volunteercode = $volunteerRecord->code;
				if ($typeResultRecord->validate()) {
					$typeResultRecord->save();
				}
			}
		}
		$this->renderPartial('ok');
	}

	public function wizardStart($event) {
		$event->handled = true;
	}

	public function wizardInvalidStep($event) {
		Yii::app()->getUser()->setFlash('notice', $event->step . ' is not a vaild step in this wizard');
	}

	public function keyWizardProcessStep($event) {
		$modelName = $event->step;
		$model = new $modelName();
		$model->attributes = $event->data;
		$form = $model->getForm();

		// Note that we also allow sumission via the Save button
		if (($form->submitted() || $form->submitted('save_draft')) && $form->validate()) {
			$event->sender->save($model->attributes);
			$event->handled = true;
		} else {
			switch ($modelName) {
				case 'KeyReader':
				case 'Challenge':
				case 'Volunteer':
				case 'Introduction':
					$this->render(strtolower($modelName), compact('form', 'event'));
					break;
				case 'Summary':
					$volunteerHash = $this->enter();
					$this->render(strtolower($modelName), compact('form', 'event', 'volunteerHash'));
					$this->reset();
					break;
				default:
					$this->render('form', compact('form', 'event'));
					break;
			}

		}
	}

	public function processKeyReaderStep($event, $form) {
		$data = array('event' => $event, 'form' => $form);
		$this->render('keyreader', $data);
	}

	public function wizardFinished($event) {
		return true;

	}

	public function wizardSaveDraft($event) {

	}

}
