<?php 
/*
 *
 * @package		ARI Smart Content
 * @author		ARI Soft
 * @copyright	Copyright (c) 2011 www.ari-soft.com. All rights reserved
 * @license		GNU/GPL (http://www.gnu.org/copyleft/gpl.html)
 * 
 */

(defined('_JEXEC') && defined('ARI_FRAMEWORK_LOADED')) or die;

require_once JPATH_ADMINISTRATOR . '/components/com_arismartcontent/kernel/class.AriKernel.php';
require_once JPATH_LIBRARIES . '/arismartcontent/htmltable/helper.php';

AriKernel::import('Data.DataFilter');
AriKernel::import('Application.ARISmartContent.Providers.ProvidersHelper');

class AriSmartContentLibraryArismartcontentDatatableAjaxDispatcher
{
	function ajax_getData()
	{
		$jInput = JFactory::getApplication()->input;
		$sourceId = $jInput->request->get('sourceId', null, 'int');
		$sourceData = AriSmartContentProvidersHelper::resolveSource($sourceId);

		if (!AriSmartContentProvidersHelper::isSupportServerSide($sourceData['provider'], $sourceData['source']))
			return null;
		
		$filter = $this->getFilter($sourceData);

		$data = AriSmartContentProvidersHelper::getData($sourceData, $filter);
		$totalRecords = AriSmartContentProvidersHelper::getTotalRecords($sourceData, null);

		$filter->setConfigValue('startOffset', 0);
		$filter->setConfigValue('limit', null);
		$filteredTotalRecords = AriSmartContentProvidersHelper::getTotalRecords($sourceData, $filter);

		return array(
			'draw' => $jInput->request->get('draw'),
			'recordsTotal' => $totalRecords,
			'recordsFiltered' => $filteredTotalRecords,
			'data' => $this->prepareData($data, $sourceData, $filter)
		);
	}

	private function getFilter($sourceData)
	{
		$jInput = JFactory::getApplication()->input;
		$filter = new AriDataFilter();

		$startOffset = $jInput->request->get('start', null, 'INT');
		$limit = $jInput->request->get('length', null, 'INT');

		$search = $jInput->request->get('search', null, 'RAW');
		$search = (is_array($search) && !empty($search['value'])) ? $search['value'] : null;

		if (!empty($search))
		{
			$filterPatterns = array(
			);

			foreach ($sourceData['columns'] as $colIdx => $column)
			{
				$col = !empty($column['original']) ? $column['original'] : $column['name'];

				$columnSettings = AriSmartContentFormattersHelper::getColumnSettings($sourceData['settings'], $column['name'], $colIdx);
				if ($columnSettings && isset($columnSettings['searchable']) && $columnSettings['searchable'])
					$filterPatterns[] = array(
						'field' => $col,
						'op' => 'LIKE',
						'value' => $search
					);
			}

			if (count($filterPatterns) > 0)
				$filter->setConfigValue('filter', $filterPatterns);
		}

		$reqColumns = $sort = $jInput->request->get('columns', null, 'RAW');
		$reqOrdering = $sort = $jInput->request->get('order', null, 'RAW');

		if (is_array($reqOrdering) && count($reqOrdering) > 0)
		{
			$hiddenColumns = AriSmartContentFormattersHelper::getHiddenColumns($sourceData['columns'], $sourceData['settings']);
			$visibleColumns = array();
			$cIdx = 0;
			foreach ($sourceData['columns'] as $column)
			{
				if (!in_array($cIdx, $hiddenColumns))
					$visibleColumns[] = $column['name'];

				++$cIdx;
			}

			$order = array();
			foreach ($reqOrdering as $reqColOrder)
			{
				$idx = intval(AriUtils::getParam($reqColOrder, 'column'), 10);
				if ($idx < 0)
					continue ;

				$reqCol = isset($reqColumns[$idx]) ? $reqColumns[$idx] : null;
				if (!$reqCol)
					continue ;

				$sortable = (AriUtils::getParam($reqCol, 'orderable', 'false') == 'true');
				if (!$sortable || !isset($visibleColumns[$idx]))
					continue ;

				$sortName = $visibleColumns[$idx];
				$sortOrder = strtolower(AriUtils::getParam($reqColOrder, 'dir', 'asc'));
				if ($sortOrder != 'asc' && $sortOrder != 'desc')
					$sortOrder = 'asc';

				$order[] = array(
					'field' => $sortName,
					'dir' => $sortOrder
				);
			}

			if (count($order) > 0)
			{
				$firstOrder = array_shift($order);
				
				$filter->setConfigValue('sortField', $firstOrder['field']);
				$filter->setConfigValue('sortDirection', $firstOrder['dir']);
				
				if (count($order) > 0)
					$filter->setConfigValue('secondarySorting', $order);
			}
		}	

		$filter->setConfigValue('startOffset', $startOffset);
		$filter->setConfigValue('limit', $limit);

		return $filter;
	}
	
	private function prepareData($srcData, $sourceData, $filter)
	{
		$destData = array();
		$columnsSettings = $sourceData['settings'];
		$hiddenColumns = AriSmartContentFormattersHelper::getHiddenColumns($sourceData['columns'], $columnsSettings);

		$rowIdx = 0;
		foreach ($srcData as $dataItem)
		{
			$colIdx = 0;
			$destDataItem = array();
			foreach ($dataItem as $colKey => $value)
			{
				if (in_array($colIdx, $hiddenColumns))
				{
					++$colIdx;
					continue ;
				}

				$columnSettings = AriSmartContentFormattersHelper::getColumnSettings($columnsSettings, $colKey, $colIdx);
				$destDataItem[] = AriSmartContentWidgetHtmlTableHelper::formatValue($value, $colIdx, $columnSettings);

				++$colIdx;
			}

			$destDataItem['DT_RowClass'] = 'ari-tbl-row-' . $rowIdx;
			$destData[] = $destDataItem;
			++$rowIdx;
		}

		return $destData;
	}
}