<?php
final class StartAction extends Action {
    /**
     * @var StartDao
     */
    protected $dao = NULL;
    /**
     * @var StartDto
     */
    protected $dto = NULL;
    public function __construct() {
    }
    /**
     * @return StartDto
     */
    public function getDto() {
        return $this->dto;
    }
    public function index() {
        $this->response->noCache();
        $key = 'uid_' . $this->dto->getUno() . '_' . $this->dto->getTno();
        if (!$uniqueId = $this->session->getCookieValue($key, 0)) {
            $uniqueId = md5(uniqid('', TRUE));
            $this->dao->replaceStart($uniqueId, $this->dto->getUno(), $this->dto->getTno());
        }
        $res = $this->dao->selectStart($uniqueId, $this->dto->getUno(), $this->dto->getTno());
        $this->dto->setUid($uniqueId);
        $this->session->setCookieValue($key, $uniqueId, time() + 7 * 24 * 3600);
        foreach ($res as $row) {
            $this->dto->setEntry($row['entry_no']);
            $this->dto->setImage($row['entry_image']);
            $this->dto->setComment($row['comment']);
        }
        return new Forward();
    }
    public function apply() {
        $this->response->noCache();
        $key = 'uid_' . $this->dto->getUno() . '_' . $this->dto->getTno();
        if (!$this->session->getCookieValue($key, 0)) {
            return new Redirect();
        }
        $this->dao->deleteStart($this->dto->getUid(), $this->dto->getWinner());
        $res = $this->dao->selectStart($this->dto->getUid(), $this->dto->getUno(), $this->dto->getTno());
        if (count($res) != 2) {
            $this->session
                    ->setCookieValue('uid_' . $this->dto->getUno() . '_' . $this->dto->getTno(), '', time() - 3600);
            $this->dao->clearStart($this->dto->getUid());
            return new Redirect('winner',
                    array('uno' => $this->dto->getUno(), 'tno' => $this->dto->getTno(), 'eno' => $res[0]['entry_no']));
        }
        foreach ($res as $row) {
            $this->dto->setEntry($row['entry_no']);
            $this->dto->setImage($row['entry_image']);
            $this->dto->setComment($row['comment']);
        }
        return new Forward();
    }
}
// EOF.
