<?php

class AVForums_Competitions_Deferred_Competition extends XenForo_Deferred_Abstract
{
	public function execute(array $deferred, array $data, $targetRunTime, &$status)
	{
		$data = array_merge(array(
			'position' => 0,
			'batch' => 70
		), $data);
		$data['batch'] = max(1, $data['batch']);

		/* @var $competitionModel AVForums_Competitions_Model_Competition */
		$competitionModel = XenForo_Model::create('AVForums_Competitions_Model_Competition');

		/* @var $entryModel AVForums_Competitions_Model_Entry */
		$entryModel = XenForo_Model::create('AVForums_Competitions_Model_Entry');

		$competitionIds = $competitionModel->getCompetitionIdsInRange($data['position'], $data['batch']);
		if (sizeof($competitionIds) == 0)
		{
			return true;
		}

		foreach ($competitionIds AS $competitionId)
		{
			$data['position'] = $competitionId;

			/* @var $competitionWriter AVForums_Competitions_DataWriter_Competition */
			$competitionWriter = XenForo_DataWriter::create('AVForums_Competitions_DataWriter_Competition', XenForo_DataWriter::ERROR_SILENT);
			if ($competitionWriter->setExistingData($competitionId))
			{
				$competitionWriter->set('competition_entry_count', $entryModel->countEntries($competitionId));
				$competitionWriter->set('competition_correct_count', $entryModel->countCorrectEntriesForCompetition($competitionId));
				$competitionWriter->set('competition_optin_count', $entryModel->countOptInsForCompetition($competitionId));
				$competitionWriter->save();
			}
		}

		$actionPhrase = new XenForo_Phrase('rebuilding');
		$typePhrase = new XenForo_Phrase('avforums_competitions_competition_stats');
		$status = sprintf('%s... %s (%s)', $actionPhrase, $typePhrase, XenForo_Locale::numberFormat($data['position']));

		return $data;
	}

	public function canCancel()
	{
		return true;
	}
}