<?php
  
class Dark_PostRating_Deferred_PostCache extends XenForo_Deferred_Abstract {
	
	const PER_PAGE = 20000;
	
	public function execute(array $deferred, array $data, $targetRunTime, &$status){
		$data = array_merge(array(
			'page' => 0,
		), $data);
			
		/* @var Dark_PostRating_Model */
		$ratingModel = XenForo_Model::create('Dark_PostRating_Model');
		
		$posts = $ratingModel->getPagedPosts($data['page'], self::PER_PAGE, array(
			'postrating' => true,
		));
		
		if(empty($posts))
			return false;
			
		foreach($posts as &$post){
			$ratingModel->updatePostCacheForPost($post, true);
		}
		
		$rbPhrase = new XenForo_Phrase('rebuilding');
		$typePhrase = new XenForo_Phrase('dark_postrating_post_cache');
		$status = sprintf('%s... %s (%s)', $rbPhrase, $typePhrase, XenForo_Locale::numberFormat($data['page'] * self::PER_PAGE));

		$data['page'] ++;
		
		return $data;		
	}
		
	public function canCancel(){
		return true;
	}
}