<?php
/**
 * @package     Cherry Picker for Virtuemart
 * @subpackage  Manufacturer View
 * @author		Maksym Stefanhuck
 * @copyright   Copyright (C) 2009 - 2014 Galt.md. All rights reserved.
 * @license     GNU General Public License version 2 or later; see COPYING.txt
 */

namespace cherrypicker;
defined('_JEXEC') or die;

require_once(CP_BASEPATH .'views/submodule.php');

use \JModuleHelper;
use \JRequest;
use \JText;
use \VmConfig;
use \JFile;

if (!class_exists('VmConfig')) {
	require_once(JPATH_ADMINISTRATOR .'/components/com_virtuemart/helpers/config.php');
	VmConfig::loadConfig();
}

jimport('joomla.application.module.helper');

class ManufacturerView extends SubmoduleView implements SubmoduleViewInterface {
	private $config;
	private $availableValues;
	private $options;
	private $_selected_values;
	//private $_hide;

	public static function defaults() {
		return array(
			"show" => 0,
			"type" => "link",
			"template" => "",
			"selecttype" => "single",
			"style" => "list",
			"use_dropdown_ajax" => 0,
			"dropdown_popup_width" => '',
			"shows" => "name", // name, image, all
			"collapsed" => CP_TOGGLE_COLLAPSE_NONE,
			"quickrefine" => 0,
			"quickrefine_hidestyle" => "default", // see quickrefine api for options
			"hide" => CP_HIDE_NONE,
			"seemore_size" => "",
			"seemore_ajax" => 0,
			"seemore_anchor" => "bottom",
			"scroll_size" => "",
			"columns" => 0,
			"onselect_update_filters" => 0,
			"onselect_update_products" => 0,
			"liveresult" => 0,  // Joomla option type="checkbox" will have value unset if unchecked.
			"show_count" => 0,	// In such case this value will be returned. If the value is set to 1
			"show_empty_values" => 0, // the option will practially be always 1.
			"show_clear_link" => 0,   // So defaults should be set to 0s.
			"sort" => "asc",  // options: asc, desc, fastseller
			"selected_values_ontop" => 0,
			//"select_step_by_step" => 0,
			//"values_threshold" => 0,	// number of values submodule should have to be displayed
			//"chosen" => 0,
			//"rules" => ""
		);
	}

	function __construct(Config $config) {
		$this->config = $config;
		$options = self::defaults();

		$onselect_json = $this->config->get('manufacturer_onselect');
		if ($onselect_json) {
			$onselect = json_decode($onselect_json, true);
			$options['onselect_update_products'] = (int)in_array('products', $onselect);
			$options['onselect_update_filters'] = (int)in_array('filters', $onselect);
		}

		$hide_json = $this->config->get('manufacturer_hideoptions');
		if ($hide_json) {
			$vars = json_decode($hide_json, true);
			$options = array_merge($options, $vars);
		}

//echo '<pre>';
//print_r($options);

		$this->options = $options;
	}

	public function display() {
		$config = $this->config;
		$module_name = CherryPicker::contextModule()->name();
		//$template = $this->options['template'];
		$template = '';

		//require(JModuleHelper::getLayoutPath($module_name, 'category_js'));
		if ($this->type() == 'manufacturer_select') {
			require(JModuleHelper::getLayoutPath($module_name, ($template ? $template : 'manufacturer_select')));
		} else {
			//if ($this->options['style'] == 'list')
			$style = $config->get('manufacturer_style', 'list');
			require(JModuleHelper::getLayoutPath($module_name, $style));
			//else
				//require(JModuleHelper::getLayoutPath($module_name, 'dropdown'));
		}
	}

	public function js() {
		$module_name = CherryPicker::contextModule()->name();
		require(JModuleHelper::getLayoutPath($module_name, 'manufacturer_js'));
	}

	public function displayName() {
		return 'manufacturer';
	}

	public function hasDisplay() {
		if (! $this->config->get('manufacturer_show'))
			return false;

		$valuesCount = count($this->availableValues());
		if (! $valuesCount)
			return false;

		return true;
		//return ($this->config->get('manufacturer_show') ||
				//JRequest::getVar('virtuemart_manufacturer_id', 0));
	}

	public function hasJs() {
		$added = isset($GLOBALS['cherrypicker_manufacturer_js_added']);
		//if (! $added)
			//$GLOBALS['cherrypicker_manufacturer_js_added'] = 1;
		return ( !$this->hasDisplay()
				&& JRequest::getVar('virtuemart_manufacturer_id', 0));
	}

	public function type() {
		return $this->config->get('manufacturer_type', 'link');
	}

	public function title() {
		return JText::_($this->config->get('string_manufacturers', 'CP_MANUFACTURERS'));
	}

	public function name() {
		return 'manufacturer';
	}

	public function urlname() {
		return 'brand';
	}

	public function units() {
		return '';
	}

	public function template() {
		return false;
	}

	public function collapsed() {
		return $this->config->get('manufacturer_collapsed', CP_TOGGLE_COLLAPSE_NONE);
	}

	public function useDropdownAjax() {
		return false;
	}

	public function popupWidth() {
		return $this->option('dropdown_popup_width');
	}

	public function option($name, $default = false) {
		$value = isset($this->options[$name]) ? $this->options[$name] : $default;
		return $this->config->get('manufacturer_'. $name, $value);


		//switch ($name) {
		//	case 'selecttype':
		//		return 'single';

		//	case 'show_count':
		//		return $this->config->get('manufacturer_show_count', $default);

		//	case 'show_empty_values':
		//		return $this->config->get('manufacturer_show_empty', $default);

		//	case 'selected_values_ontop':
		//		return $this->config->get('manufacturer_selected_values_ontop', $default);

		//	case 'quickrefine':
		//		return $this->config->get('manufacturer_quickrefine', $default);

		//	case 'show_clear_link':
		//		return $this->config->get('manufacturer_show_clear_link', $default);

		//	case 'columns':
		//		return $this->config->get('manufacturer_columns', $default);

		//	case 'liveresult':
		//		return $this->config->get('manufacturer_liveresult', $default);

		//	case 'hide':
		//		return $this->hide('type');

		//	case 'seemore_size':
		//		return $this->hide('seemore_size');

		//	case 'seemore_anchor':
		//		return $this->hide('seemore_anchor');

		//	case 'seemore_ajax':
		//		return $this->hide('seemore_ajax');

		//	case 'scroll_height':
		//		return $this->hide('scroll_height');

		//	case 'onselect_update_products':
		//		$onselect_json = $this->config->get('manufacturer_onselect');
		//		$onselect = ($onselect_json) ? json_decode($onselect_json, true) : array();
		//		return (int)in_array('products', $onselect);

		//	case 'onselect_update_filters':
		//		$onselect_json = $this->config->get('manufacturer_onselect');
		//		$onselect = ($onselect_json) ? json_decode($onselect_json, true) : array();
		//		return (int)in_array('filters', $onselect);

		//	default:
		//		return false;
		//}
	}

	public function uniqueViewId() {
		$id = CherryPicker::contextModule()->id();
		return 'cp'. $id .'_'. $this->displayName();
	}

	public function showValueImage() {
		$shows = $this->config->get('manufacturer_shows');
		$type = $this->type();
		return ($type != 'select' && ($shows == 'image' || $shows == 'all'));
	}

	public function showValueText() {
		$shows = $this->config->get('manufacturer_shows');
		$type = $this->type();
		return ($type == 'select' || ($shows == 'name' || $shows == 'all'));
	}

	public function selectedValues() {
		if (! $this->_selected_values) {
			$selectedValues = ManufacturersModel::getInstance()->selectedValues();
			if ($this->showValueImage())
				$this->setFullImagePaths($selectedValues);
				//foreach ($selectedValues as &$value)
			//}
			$this->_selected_values = $selectedValues;
		}
		//return JRequest::getVar('virtuemart_manufacturer_id', 0);
		return $this->_selected_values;
	}

	public function selectedId() {
		return JRequest::getVar('virtuemart_manufacturer_id', 0);
	}

	public function removeValueUrl($value) {
		return ManufacturersModel::getInstance()->removeValueUrl($value);
	}

	public function removeValuesUrl() {
		return ManufacturersModel::getInstance()->removeValuesUrl();
	}

//	public function hide($name) {
//		if ($this->_hide === null) {
//			$defaults = array(
//				"type" => "0",
//				"seemore_size" => "",
//				"seemore_anchor" => "bottom",
//				"seemore_ajax" => 0,
//				"scroll_size" => ""
//			);
//			$vars = array();
//			$options = $this->config->get('manufacturer_hide');
//			if ($options) {
//				$vars = json_decode($options, true);
//			}
//			$this->_hide = array_merge($defaults, $vars);
//		}
//
//		return $this->_hide[$name];
//	}

	private function setFullImagePaths(&$values) {
		$useThumb = true;
		if ($useThumb) {
			$width = VmConfig::get('img_width', 90);
			$height = VmConfig::get('img_height', 90);
			$path = VmConfig::get('media_manufacturer_path');
		}
		$urlbase = \JURI::base();
		foreach ($values as &$value) {
			if (! $value['image']) continue;
			if ($useThumb) {
				$basename = basename($value['image']);
				$filename = JFile::stripExt($basename);
				$extension = strtolower(JFile::getExt($basename));
				$value['thumb'] = $urlbase . $path . 'resized/'. $filename
					.'_'. $width .'x'. $height .'.'. $extension;
			}
			$value['image'] = $urlbase . $value['image'];
		}
	}

	public function availableValues() {
		if ($this->availableValues) return $this->availableValues;
		$model = ManufacturersModel::getInstance();
		$config = $this->config;

		//$show_empty_values = $config->get('manufacturer_show_empty_values');
		$show_empty_values = $this->option('show_empty_values');
		//$sort = $config->get('manufacturer_sort', 'asc');
		$sort = $this->option('sort', 'asc');
		$limit = 0;
		$seemore_ajax = 0;

		$type = $this->type();
		if ($type == 'select') {
			$url = false;
		} else {
			$url = ($type == 'checkbox') ? false : true;
			$display = JRequest::getVar('display', '');
			$seemore_ajax = ($this->option('hide') == CP_HIDE_SEEMORE
				&& $this->option('seemore_size') !== ''
				&& $this->option('seemore_ajax')
				&& $display != 'seemore');

			// increase by 1 to see later whether there is an actual need
			// to show See more.. prompt
			if ($seemore_ajax)
				$limit = $this->option('seemore_size') + 1;
		}

		//$withCount = $config->get('manufacturer_show_count');
		$withCount = $this->option('show_count');
		//$shows = $config->get('manufacturer_shows');
		//$image = ($shows == 'image' || $shows == 'all');
		$image = $this->showValueImage();
		$availableValues = $model->availableValues($withCount, $image, $limit, $url, 'single', $sort);
		//$availableValues = $model->availableValues(true, true, 0, true, 'single', $sort);

		$selectedAliases = $model->selectedAliases();
		if ($show_empty_values) {
			$only_submodules = array("category" => true, "shopper" => 1);
			$availableValuesAll = $model->availableValues(false, false, $limit, false, '', $sort, $only_submodules);

//echo '<pre>';
//echo nl2br("\n\n");
//print_r($availableValues);
//echo nl2br("\n\n");
//print_r($availableValuesAll);

			foreach ($availableValuesAll as $i => $valueA) {
				$found = false;
				foreach ($availableValues as &$valueB)
					if ($valueB['name'] == $valueA['name']) {
						/*
						 * we will need somehow to distinquish empty values
						 * from found values, so mark found values with 1s
						 */
						if (! $withCount) $valueB['count'] = 1;
						$found = true;
						break;
					}
				unset($valueB);
				if (! $found) {
					//$new = array(
					//	"name" => $valueA['name'],
					//	"alias" => $valueA['alias']
					//);
					$new = $valueA;
					$new['count'] = 0;
					if ($url)
						$new['url'] = (in_array($valueA['alias'], $selectedAliases)) ?
							$model->removeValueUrl($valueA) : '';
					array_splice($availableValues, $i, 0, array($new));
				}
			}
		}

//echo '<pre>';
//print_r($availableValues);
//die;
		foreach ($availableValues as &$value) {
			$value['selected'] = in_array($value['alias'], $selectedAliases);
		}
		unset($value); // must unset last value reference

		if ($image) {
			$this->setFullImagePaths($availableValues);
//			$useThumb = true;
//			if ($useThumb) {
//				$width = VmConfig::get('img_width', 90);
//				$height = VmConfig::get('img_height', 90);
//				$path = VmConfig::get('media_manufacturer_path');
//			}
//			$urlbase = \JURI::base();
//			foreach ($availableValues as &$value) {
//				if (! $value['image']) continue;
//				if ($useThumb) {
//					$basename = basename($value['image']);
//					$filename = JFile::stripExt($basename);
//					$extension = strtolower(JFile::getExt($basename));
//					$value['thumb'] = $urlbase . $path . 'resized/'. $filename
//						.'_'. $width .'x'. $height .'.'. $extension;
//				}
//				$value['image'] = $urlbase . $value['image'];
//			}
		}

//echo '<pre>';
//print_r($availableValues);
//die;

		//$remainingValues = $selectedAliases;
		//foreach ($availableValues as &$value)
		//	if (( $pos = array_search($value['alias'], $remainingValues) ) !== false) {
		//		$value['selected'] = true;
		//		array_splice($remainingValues, $pos, 1);
		//	} else {
		//		$value['selected'] = false;
		//	}


		//if ($config->get('manufacturer_selected_values_ontop') && $selectedValues) {
		$selectedValues = $this->selectedValues();
		if ($this->option('selected_values_ontop') && $selectedValues) {
			$selected = $not_selected = array();
			foreach ($availableValues as $value)
				//if (( $pos = array_search($value['name'], $selectedValues) ) !== false) {
				if ($value['selected']) {
					$selected[] = $value;
					//array_splice($selectedValues, $pos, 1);
				} else {
					$not_selected[] = $value;
				}
//print_r($selected);
//print_r($not_selected);
			if ($seemore_ajax) {
				foreach ($selectedValues as $value) {
					$add = true;
					foreach ($availableValues as $aval)
						if ($aval['alias'] == $value['alias']) {
							$add = false;
							break;
						}
				//foreach ($remainingValues as $value) {
					if ($add) {
						$new = array(
							"name" => $value['name'],
							"alias" => $value['alias'],
							"count" => '',
							"selected" => true);
						if ($url)
							$new['url'] = $model->removeValueUrl($value);
						$selected[] = $new;
					}
				}
			}

			$availableValues = array_merge($selected, $not_selected);
		}

		$this->availableValues = $availableValues;
		return $availableValues;
	}

}
