<?php

class AVForums_Competitions_AlertHandler_Competition extends XenForo_AlertHandler_Abstract
{
	protected $_competitionModel;

	/**
	 * Fetches the content required by alerts.
	 *
	 * @param array $contentIds
	 * @param XenForo_Model_Alert $model Alert model invoking this
	 * @param integer $userId User ID the alerts are for
	 * @param array $visitor Information about the viewing user (keys: user_id, permission_combination_id, permissions)
	 *
	 * @return array
	 */
	public function getContentByIds(array $contentIds, $model, $userId, array $visitor)
	{
		$competitionModel = $this->_getCompetitionModel();

		$competitions = $competitionModel->getCompetitions(array(
			'competition_id' => $contentIds
		), array(
			'join' => AVForums_Competitions_Model_Competition::FETCH_USER
		));

		return $competitions;
	}

	/**
	 * Determines if the rating is viewable.
	 * @see XenForo_AlertHandler_Abstract::canViewAlert()
	 */
	public function canViewAlert(array $alert, $content, array $visitor)
	{
		$competitionModel = $this->_getCompetitionModel();
		$content = $competitionModel->prepareCompetition($content);

		if (!$competitionModel->canViewCompetitions())
		{
			return false;
		}

		/* @var $userModel XenForo_Model_User */
		$userModel = XenForo_Model::create('XenForo_Model_User');

		$restrictedViewGroups = false;
		if (!in_array('-1', $content['view_user_groups']))
		{
			$restrictedViewGroups = true;
		}

		if ($restrictedViewGroups)
		{
			if (!$userModel->isMemberOfUserGroup($visitor, $content['view_user_groups'], true))
			{
				return false;
			}
		}

		return true;
	}

	/**
	 * @return AVForums_Competitions_Model_Competition
	 */
	protected function _getCompetitionModel()
	{
		if (!$this->_competitionModel)
		{
			$this->_competitionModel = XenForo_Model::create('AVForums_Competitions_Model_Competition');
		}

		return $this->_competitionModel;
	}
}