<?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') or die;

$adminPath = dirname(__FILE__) . '/';
require_once $adminPath . 'kernel/class.AriKernel.php';
require_once $adminPath . 'defines.php';

AriKernel::import('Application.ARISmartContent.Utils.Helper');

jimport('joomla.installer.helper');
jimport('joomla.installer.installer');

function com_uninstall()
{
	$app = JFactory::getApplication();
	
	$lang = JFactory::getLanguage();
	$lang->load('com_arismartcontent');
	
	$cfg = AriSmartContentHelper::getConfig();
	$cleanUninstall = $cfg->get('CleanUninstall', false);
	
	if (!$cleanUninstall)
		return true;

	$db = JFactory::getDBO();
	$db->setQuery(
		'DROP TABLE IF EXISTS 
			#__arismartcontent_config,
			#__arismartcontent_formatters,
			#__arismartcontent_providers,
			#__arismartcontent_provider_categories,
			#__arismartcontent_provider_settings,
			#__arismartcontent_provider_settings_groups,
			#__arismartcontent_provider_sources,
			#__arismartcontent_provider_source_types'
	);
	$db->query();

	$cfg->removeCache();

	// remove packages
	$db->setQuery('
		SELECT 
			extension_id,
			name,
			type,
			element 
		FROM 
			#__extensions 
		WHERE  
			(type = "package" AND element LIKE "pkg_arismartcontent_%")
			OR
			(type = "plugin" AND element IN ("arismartcontent", "arismartcontentmodule", "arismartcontentloadmodule"))
		'
	);
	$smartContentApps = $db->loadObjectList();

	if ($db->getErrorNum())
	{
		$app->enqueueMessage($db->getErrorMsg(), 'error');
		return false;
	}

	if (is_array($smartContentApps))
	{
		$installer = new JInstaller();
		foreach ($smartContentApps as $smartContentApp)
		{
			if (!$installer->uninstall($smartContentApp->type, $smartContentApp->extension_id))
			{
				$app->enqueueMessage(
					sprintf('[%1$s].[%2$s] was not uninstalled.',
						$smartContentApp->type, 
						$smartContentApp->name
					), 
					'warning'
				);
			}
		}
	}

	return true;
}