<?php
final class EntryAction extends Action {
    /**
     * @var EntryDao
     */
    protected $dao = NULL;
    /**
     * @var EntryDto
     */
    protected $dto = NULL;
    public function __construct() {
    }
    /**
     * @return EntryDto
     */
    public function getDto() {
        return $this->dto;
    }
    public function index() {
        return new Forward();
    }
    public function apply() {
        $this->file->setInputName('entry_image');
        if (!$this->_isValid()) {
            return new Forward();
        }
        $entryNo = $this->dao->selectEntry($this->dto->getUno(), $this->dto->getTno());
        $limitNo = $this->dao->selectTournament($this->dto->getUno(), $this->dto->getTno());
        if ($entryNo > $limitNo) {
            $this->error->add(MessageBehavior::getMessage('ERR006', array('ENTRY_TOURNAMENT', 'REASON_LIMIT')));
            return new Forward();
        }
        $path = WEB . 'resource' . DIRECTORY_SEPARATOR;
        $dest = md5_file($this->file->getTmpName()) . '_' . date('Ymd_His') . '.jpg';
        move_uploaded_file($this->file->getTmpName(), $path . $dest);
        $name = $this->file->getName();
        $this->dao
                ->insertEntry($this->dto->getUno(), $this->dto->getTno(), $entryNo, $this->dto->getNickname(), $dest,
                        $name, $this->dto->getComment());
        if ($entryNo == $limitNo) {
            $this->dao->updateTournament($this->dto->getUno(), $this->dto->getTno());
        }
        return new Redirect();
    }
    private function _isValid() {
        $valid = TRUE;
        if (!Validator::required($this->dto->getNickname())) {
            $this->error->add(MessageBehavior::getMessage('ERR004', 'NICKNAME'));
            $valid = FALSE;
        }
        if (!Validator::required($this->dto->getComment())) {
            $this->error->add(MessageBehavior::getMessage('ERR004', 'COMMENT'));
            $valid = FALSE;
        }
        if ($this->file->getSize() == 0) {
            $this->error->add(MessageBehavior::getMessage('ERR004', 'UPLOAD_FILE'));
            $valid = FALSE;
        } else {
            if (!StringUtil::endWith($this->file->getType(), 'jpeg')) {
                $this->error->add(MessageBehavior::getMessage('ERR005', array('UPLOAD_FILE', 'JPEG')));
                $valid = FALSE;
            }
            if ($this->file->getSize() > 512000) {
                $this->error->add(MessageBehavior::getMessage('ERR005', array('UPLOAD_FILE', 'U_500KB')));
                $valid = FALSE;
            }
        }
        return $valid;
    }
}
// EOF.
