<?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;

AriKernel::import('Joomla.Models.Model');
AriKernel::import('Joomla.Database.DBUtils');
AriKernel::import('Utils.Utils');

class AriSmartContentModelProvidersourcetype extends AriModel 
{
	function getSourceTypesByCategory($catName)
	{
		$db = $this->getDBO();
		$db->setQuery(
			sprintf(
				'SELECT
					ST.SourceTypeId,
					ST.Name,
					P.Name AS Provider,
					ST.SystemName
				FROM
					#__arismartcontent_provider_source_types ST INNER JOIN #__arismartcontent_providers P
						ON ST.ProviderId = P.ProviderId
					INNER JOIN #__arismartcontent_provider_categories C
						ON P.CategoryId = C.CategoryId
				WHERE
					C.SystemName = %1$s
				',
				$db->Quote($catName)
			)
		);
		$types = $db->loadObjectList();
		if ($db->getErrorNum())
		{
			JError::raiseError(
				500, 
				JText::sprintf(
					'COM_ARISMARTCONTENT_ERROR_SQL_QUERY', 
					__CLASS__ . '::' . __FUNCTION__ . '()', 
					$db->getQuery(), 
					$db->getErrorMsg()
				)
			);
			
			return null;
		}
		
		foreach ($types as $type)
		{
			$type->FullName = JText::_($type->Provider) . ' - ' . JText::_($type->Name);
		}
		
		$sort = new AriSortUtils('FullName', 'asc');
		usort($types, array(&$sort, 'sort'));

		return $types;
	}
	
	function getSourceType($id, $strictLoad = true) 
	{
		if ($strictLoad && $id < 1)
			return null;

		$sourceType = $this->getTable();
		$sourceType->load($id);
		
		if ($strictLoad && empty($sourceType->Name))
			$sourceType = null;

		return $sourceType;
	}
	
	function getTypeBySystemName($name, $strictLoad = true)
	{
		if ($strictLoad && empty($name))
			return null;

		$type = $this->getTable();
		$type->loadBySystemName($name);
		
		if ($strictLoad && $type->SystemName != $name)
			$type = null;

		return $type;
	}
}