<?php

/**
 * guests actions.
 *
 * @package    balsit
 * @subpackage guests
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class guestsActions extends sfActions
{
	public function executeIndex(sfWebRequest $request)
	{
		$this->guests = Doctrine::getTable('Guest')
		->createQuery('a')
		->execute();
	}
	public function executeHome(sfWebRequest $request)
	{
		
	}

	public function executeShow(sfWebRequest $request)
	{
		$id=$this->getCurrentId();
		$this->guest = Doctrine::getTable('Guest')->find(array($id));
		$this->forward404Unless($this->guest);
	}
	public function executeGreeting(sfWebRequest $request)
	{
		$this->forward404Unless($request->hasParameter('id'),'Bad request - ID is needed for greeting');
		$this->id=$request->getParameter('id');
		$this->getUser()->getAttributeHolder()->clear();
	}

	public function executeNew(sfWebRequest $request)
	{
		$this->form = new GuestForm();
	}

	public function executeCreate(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST),"bad method");

		$this->form = new GuestForm();

		if(!($ind = $this->processForm($request, $this->form))==false) {
			$this->getUser()->setAttribute('id',$ind);
			$this->redirect('@show');
		}
		else
		$this->setTemplate('edit');
	}

	public function executeEdit(sfWebRequest $request)
	{
		$id=$this->getCurrentId();
		$this->forward404Unless($guest = Doctrine::getTable('Guest')->find(array($id)), sprintf('Object guest does not exist (%s).', $id));
		$this->form = new GuestForm($guest);
	}

	public function executeUpdate(sfWebRequest $request)
	{
		//		die('<pre>'.print_r($request->getPostParameters(),true).'</pre>');
		$this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
		$id=$this->getCurrentId();
		$this->forward404Unless($guest = Doctrine::getTable('Guest')->find(array($id)), sprintf('Object guest does not exist (%s).', $id));
		$this->form = new GuestForm($guest);

		$params=$request->getPostParameters();
		if($this->processForm($request, $this->form))
		$this->redirect('@show');
		else
		$this->setTemplate('edit');

	}

	public function executeDelete(sfWebRequest $request)
	{
		$request->checkCSRFProtection();
		$id=$this->getCurrentId();
		$this->forward404Unless($guest = Doctrine::getTable('Guest')->find(array($id)), sprintf('Object guest does not exist (%s).', $id));
		$guest->delete();

		$this->redirect('@homepage');
	}

	protected function processForm(sfWebRequest $request, sfForm $form)
	{
		$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
		if ($form->isValid())
		{
			$guest = $form->save();
			return $guest->getId();
		}
		return false;
	}

	protected function getCurrentId()
	{
		$this->redirectUnless($this->getUser()->hasAttribute('id'),"@homepage");
		return $this->getUser()->getAttribute('id');
	}
}
