<?php
namespace cherrypicker;
defined('_JEXEC') or die;

//require_once(dirname(__FILE__) .'/../defines.php');
//require_once(CP_BASEPATH .'helpers/factory.php');

require_once(CP_BASEPATH .'views/view.html.php');
require_once('submodule.php');
//require_once('config.php');
require_once(CP_BASEPATH .'helpers/sql.php');

use \JURI;
use \JFactory;
use \JText;

ini_set('display_errors', 1);
class Module {
	private $id;
	private $name;
	private $config;
	private $view;
	private $matched_products_count = -1;


	function __construct($id) {
		$this->id = $id;

		/* Before using JText need to ensure Cherry Picker language file is
			loaded */
		$lang = JFactory::getLanguage();
		$lang->load('mod_cherry_picker');


		/*
		 * Submodules are basically data models that have single inter-module
		 * state. Therefore it's created just once.
		 * SubmoduleViews on other hand provide the configuration
		 * on how each data model should be interpreted and displayed. Views
		 * are configurable through Module Manager in Joomla!
		 */
		if (! Submodule::submodules()) {
			$config = $this->config();

			require_once(CP_BASEPATH .'models/parameters.php');
			$parametersModel = ParametersModel::getInstance();
			Submodule::add($parametersModel);

			require_once(CP_BASEPATH .'models/customfields.php');
			$customfieldsModel = CustomfieldsModel::getInstance();
			if ($customfieldsModel->tableExists()) {
				Submodule::add($customfieldsModel);
			} else {
				if ($config->get('debug'))
					trigger_error(JText::_('CP_NO_CHERRYPICKER_CUSTOMFIELDS_TABLE'));
			}

			require_once(CP_BASEPATH .'models/prices.php');
			$priceModel = PriceModel::getInstance();
			Submodule::add($priceModel);

			require_once(CP_BASEPATH .'models/category.php');
			$categoriesModel = CategoriesModel::getInstance();
			Submodule::add($categoriesModel);

			require_once(CP_BASEPATH .'models/manufacturer.php');
			$manufacturersModel = ManufacturersModel::getInstance();
			Submodule::add($manufacturersModel);
			//$manufacturersModel->addDependency($priceModel);

			require_once(CP_BASEPATH .'models/stock.php');
			$stockModel = StockModel::getInstance();
			Submodule::add($stockModel);

			require_once(CP_BASEPATH .'models/rating.php');
			$ratingModel = RatingModel::getInstance();
			Submodule::add($ratingModel);

			if ($config->get('use_shoppergroups')) {
				require_once(CP_BASEPATH .'models/shopper.php');
				$shopperModel = ShopperModel::getInstance();
				Submodule::add($shopperModel);
			}

			// todo: need keyword search submodule?
		}
	}

	//public function submodules() {
	//}

	//public function config(Config $config = null) {
	public function config($config = null) {
		if ($config) {
			$this->config = $config;
		} else {
			//if (! $this->config) {
			//	try {
			//		$this->config = new Config();
			//		$this->config->init($this->id);
			//	} catch (PHPException $e) {
			//		return null;
			//	}
			//}
			return $this->config;
		}
	}


	//public function view() {
	//	if (! $this->view) {
	//		try {
	//			$this->view = new ModuleView($this);
//ec//ho '<pre>';
//va//r_dump($this->view);
	//		} catch (PHPException $e) {
	//			$this->view = new ViewLegacyHelper();
	//		}
	//	}
	//	return $this->view;
	//}


	public function id() {
		return $this->id;
	}


	public function name($name = null) {
		if ($name === null) {
			return $this->name;
		} else {
			$this->name = $name;
		}
	}

	public function urlbase() {
		return JURI::base() .'modules/'. $this->name .'/';
	}


	public function matchedProductsCount() {
		if ($this->matched_products_count == -1) {
			$db = JFactory::getDBO();
			$joins = array();
			$wheres = array();
			$query = Sql::query();
			$products_table = Sql::table('#__virtuemart_products', 'p');

			$query->select("COUNT(DISTINCT p.`virtuemart_product_id`)")
				->from($products_table)
				//->where("p.`published`=1");
				->where("(p.`published`=1 OR p.`published` IS NULL)");

			//$wheres[] = "p.`published`=1";
			//$on_column = "p.`virtuemart_product_id`";
			$on_column = Sql::column('virtuemart_product_id', $products_table);
			foreach (Submodule::submodules() as $submodule) {
				//$name = $submodule->submoduleName();
				//$table = $name == 'stock' ? 'p' : '';
				if (( $j = $submodule->sqlJoins($on_column) ))
					$joins = array_merge($joins, $j);
				if (( $w = $submodule->sqlWheres() ))
					$wheres = array_merge($wheres, $w);
			}

			foreach ($joins as $join) $query->join($join);
			foreach ($wheres as $where) $query->where($where);
			$query->uniquify();

			//$q = "SELECT COUNT(DISTINCT p.`virtuemart_product_id`)".
			//	" FROM (`#__virtuemart_products` as p) ".
			//	implode(' ', $joins);
			//if ($wheres) $q .= " WHERE ". implode(' AND ', $wheres);

//echo $q;

			$db->setQuery((string)$query);
			$this->matched_products_count = $db->loadResult();
//var_dump( $db );
		}
		return $this->matched_products_count;
	}


	public function reconfigureModels($activateAll = false) {
//echo 'reconfigure mod:'. $this->id;
//print_r($config);
		$config = $this->config();


		$categoriesModel = CategoriesModel::getInstance();
		$search_subtree = ($config->get('category_show_count') == 'subtree');
		$ignored_by_others = $config->get('category_ignored_by_others');
		$categoriesModel->shouldSearchSubtree($search_subtree);
		if ($activateAll || !$ignored_by_others) {
			$categoriesModel->activate();
		} else if ($ignored_by_others) {
			$categoriesModel->deactivate();
		}

		$stockModel = StockModel::getInstance();
		$stockModel->searchStockOf($config->get('stock_search_stock_of', CP_STOCK_SEARCH_PARENT));
		if ($config->get('stock_default_selected')
			&& $stockModel->selectedValue() !== 0)
		{
			$stockModel->selectedValue(1);
		}

		foreach (Submodule::submodules() as $submodule) {
			switch ($submodule->submoduleName()) {
				case 'parameter':
					if (CP_MULTIMODULE_ISOLATED_MODE) {
						if ($activateAll) {
							$submodule->activate();
							$submodule->qualificationList(array());
						} else if ($config->get('parameter_show') == CP_PARAMETER_SHOW_NONE) {
							$submodule->deactivate();
						} else {
							$submodule->activate();
							$selected_parameters = (array)$config->get('parameter_selected');
							$submodule->qualificationList($selected_parameters);
						}
					}
					break;


				case 'customfield':
					if (CP_MULTIMODULE_ISOLATED_MODE) {
						if ($activateAll) {
							$submodule->activate();
							$submodule->qualificationList(array());
						} else if ($config->get('customfield_show') == CP_CUSTOMFIELD_SHOW_NONE) {
							$submodule->deactivate();
						} else {
							$submodule->activate();
							$selected_customfields = (array)$config->get('customfield_selected');
							$submodule->qualificationList($selected_customfields);
						}
					}
					break;


				case 'price':
					if (CP_MULTIMODULE_ISOLATED_MODE) {
						if ($activateAll) {
							$submodule->activate();
						} else if ($config->get('price_enabled')) {
							$submodule->activate();
						} else {
							$submodule->deactivate();
						}
					}
					$submodule->calculationRules($config->get('price_calculation_rules', CP_CALC_RULES_NONE));
					$submodule->useCategoryCalcRules($config->get('price_use_category_calc_rules', false));
					$submodule->useMulticurrency($config->get('price_multicurrency', false));
					$submodule->useShopperGroups($config->get('use_shoppergroups', false));
					break;

			}
		}

		$this->setSubviewSearchModes();
	}


	public function setSubviewSearchModes() {
		//$selected_parameters = (array)$this->config()->get('parameter_selected');
//$v = $this->view()->getDisplayViews();
//echo '<pre>';
//print_r($v);
		foreach ($this->view()->getDisplayViews() as $view) {
			// not all models have searchMode
			$name = $view->displayName();
			if ($name == 'parameter' || $name == 'customfield') {
				$view->model()->searchMode($view->searchMode());
			}
			//	if (CP_MULTIMODULE_ISOLATED_MODE
			//		&& !in_array($view->name(), $selected_parameters))


			//				if (in_array($parameter->name(), $selected_parameters)
			//					|| in_array('producttype_'. $parameter->ptid(), $selected_parameters))
			//	{
			//		$mode = CP_SEARCHMODE_NONE;
			//	} else {
			//		$mode = $view->searchMode();
			//	}
			//	$view->model()->searchMode($mode);
			//}
		}
	}
}
