<?php
/**
 * XenForo User Albums
 *
 * @category XenForo Application
 * @package    XfRu_UserAlbums
 * @copyright  Copyright (c) 2010 XF-Russia. (http://www.xf-russia.ru)
 * @license
 * @version   $Id: DataRebuild.php 296 2011-08-23 09:33:21Z pepelac $ $Date: 2011-08-23 11:33:21 +0200 (Tue, 23 Aug 2011) $ $Revision: 296 $
 * @author Pepelac
 *
 */
class XfRu_UserAlbums_ControllerHelper_DataRebuild extends XenForo_ControllerHelper_Abstract
{
	public function rebuildData(array $input, $redirect, $submitUrl, $doRebuild = false)
	{
		$caches = $input['caches'];
		$position = $input['position'];

		$viewParams = array(
			'detailedMessage' => ''
		);

		if ($doRebuild && $caches)
		{

			$cache = array_shift($caches);
			if (!is_array($cache))
			{
				$options = array();
			} else {
				list($cache, $options) = $cache;
			}

			$rebuilt = XfRu_UserAlbums_CacheRebuilder_Abstract::getCacheRebuilder($cache)->rebuild($position, $options, $detailedMessage);
			if (is_int($rebuilt))
			{
				// still doing this one
				array_unshift($caches, array($cache, $options));
				$position = $rebuilt;

				$viewParams['detailedMessage'] = $detailedMessage;
			} else {
				$position = 0;
			}
		}

		if (!$caches)
		{
			return $this->_controller->responseRedirect(
				XenForo_ControllerResponse_Redirect::SUCCESS,
				$redirect
			);
		}

		$nextCache = reset($caches);
		if (is_array($nextCache))
		{
			list($nextCache) = $nextCache;
		}
		$nextBuilder = XfRu_UserAlbums_CacheRebuilder_Abstract::getCacheRebuilder($nextCache);

		$viewParams['rebuildMessage'] = $nextBuilder->getRebuildMessage();
		$viewParams['showExitLink'] = $nextBuilder->showExitLink();
		$viewParams['submitUrl'] = $submitUrl;
		$viewParams['elements'] = array(
			'caches' => json_encode($caches),
			'position' => $position,
			'redirect' => $redirect
		);

		return $viewParams;
	}
}