<?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.Tables.Table');
AriKernel::import('Web.JSON.JSON');
AriKernel::import('Utils.Utils');
AriKernel::import('Utils.ArrayHelper');
AriKernel::import('Utils.DateUtility');

require_once dirname(__FILE__) . '/providersourcetype.php';
require_once dirname(__FILE__) . '/providersettings.php';
require_once dirname(__FILE__) . '/formatter.php';

class AriSmartContentTableProvidersource extends AriTable
{
	var $Id;
	var $Name = '';
	var $SourceTypeId;
	var $SettingsId;
	var $FormatterId = 0;
	var $Params = null;
	var $Description = '';
	var $CreatedBy = 0;
	var $Created;
	var $ModifiedBy = 0;
	var $Modified = null;
	var $SourceType;
	var $ProviderSettings;
	var $Formatter;
	
	function __construct(&$db) 
	{
		parent::__construct('#__arismartcontent_provider_sources', 'Id', $db);
		
		$this->SourceType = new AriSmartContentTableProvidersourcetype($db);
		$this->ProviderSettings = new AriSmartContentTableProvidersettings($db);
		$this->Formatter = new AriSmartContentTableFormatter($db);

		$this->addRelation('SourceTypeId', 'SourceType');
		$this->addRelation('SettingsId', 'ProviderSettings');
		$this->addRelation('FormatterId', 'Formatter');
	}
	
	function bind($from, $ignore = array())
	{
		$ignore[] = 'Formatter';

		if (parent::bind($from, $ignore) === false)
			return false;

		if ($this->Formatter->bind(AriUtils::getParam($from, 'Formatter', array()), $ignore) === false)
			return false;

		return true;
	}

	function store($updateNulls = false)
	{
		$this->Params = $this->Params ? json_encode($this->Params) : '';

		$formatter =& $this->Formatter;
		if (!$formatter->FormatterId && empty($formatter->Name))
			$formatter->Name = $this->Name . '_' . $this->SourceType->SystemName;
		
		if ($formatter->store($updateNulls) === false)
			return false;

		$this->FormatterId = $formatter->FormatterId;

		return parent::store($updateNulls);
	}

	function load($oid = null, $reset = true)
	{
		$result = parent::load($oid, $reset);

		if (!$result)
			return $result;

		if ($this->Params)
			$this->Params = json_decode($this->Params);
			
		if ($this->ProviderSettings->Params)
			$this->ProviderSettings->Params = json_decode($this->ProviderSettings->Params);
			
		if ($this->Formatter->Data)
			$this->Formatter->Data = json_decode($this->Formatter->Data);

		return $result;
	}
}