<?php
/**
 * @package     Cherry Picker for HikaShop
 * @subpackage  Custom Field View
 * @author		Maksym Stefanhuck
 * @copyright   Copyright (C) 2009 - 2015 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;

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

class CustomfieldView extends SubmoduleView implements SubmoduleViewInterface {
	private $customfield;
	private $config;
	private $options;
	private $availableValues;

	public static function defaults() {
		return array(
			"type" => "link",
			"template" => "",
			"selecttype" => "multi",
			"style" => "list",
			"use_dropdown_ajax" => 0,
			"dropdown_popup_width" => '',
			"collapsed" => CP_TOGGLE_COLLAPSE_NONE,
			"quickrefine" => 0,
			"quickrefine_hidestyle" => "default", // see quickrefine js api for options
			"liveresult" => 0,
			"hide" => CP_HIDE_NONE,
			"seemore_size" => "",
			"seemore_ajax" => 0,
			"seemore_anchor" => "bottom",
			"scroll_size" => "",
			"trackbar" => "oneslider_exact", // oneslider_exact, oneslider_lt, twosliders
			"columns" => 0,
			"placeholder" => "",
			"onselect_update_filters" => 0,
			"onselect_update_products" => 0,
			"liveresult" => 0,
			"show_count" => 1,
			"show_empty_values" => 0,
			"show_clear_link" => 0,
			"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(Customfield $customfield, Config $config) {
	function __construct(Customfield $customfield, $config) {
		$this->customfield = $customfield;
		//$config = CPFactory::getConfiguration();
		$this->config = $config;

		$displayOptionsAll = json_decode($config->get('customfield_options'), true);
		$name = "cf_". $customfield->id();
		$displayOptions = isset($displayOptionsAll[$name]) ?
			$displayOptionsAll[$name] : array();
		$this->options = array_merge(self::defaults(), $displayOptions);
		//echo '<pre>';
		//print_r($this->options);
	}

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

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

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

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

	public function hasDisplay() {
		$type = $this->type();
		$display = JRequest::getVar('display', '');
		if ($this->option('style') == 'dropdown'
			&& $this->options['use_dropdown_ajax']
			&& $display != 'dropdown')
		{
			return true;
		}
		if ($type == 'select' && $this->options['select_step_by_step'])
			return true;
		if ($type == 'text')
			return true;
//echo ' calc avail for: '. $this->name();
		$valuesCount = count($this->availableValues());
		$threshold = $this->options['values_threshold'];
		if ($valuesCount && !($threshold && $valuesCount < $threshold)) {
			return true;
		}
		return false;
	}

	public function hasJs() {
		//return false;
		$display = JRequest::getVar('display', '');
		if ($this->option('style') == 'dropdown'
			&& $this->options['use_dropdown_ajax']
			&& $display != 'dropdown')
		{
			return true;
		}
	}

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


	public function type() {
		return $this->options['type'];
	}

	public function title() {
		$translate = $this->config->get('translate');
		$title = $this->customfield->title();
		return $translate ? JText::_($title) : $title;
	}

	public function name() {
		//return $this->customfield->name();
		return "cf_". $this->customfield->id();
	}

	public function urlname() {
		return $this->customfield->name();
	}

	public function units() {
		return '';
		//return $this->customfield->units();
	}

	public function template() {
		return $this->options['template'];
	}

	public function useDropdownAjax() {
		return $this->options['use_dropdown_ajax'];
	}

	public function popupWidth() {
		return $this->options['dropdown_popup_width'];
	}

	public function collapsed() {
		return $this->options['collapsed'];
	}
	//public function selecttype() {
	//	return $this->options['selecttype'];
	//}

	//public function showEmptyValues() {
	//	return $this->options['show_empty_values'];
	//}

	//public function showCount() {
	//	return $this->options['show_count'];
	//}

	public function uniqueViewId() {
		//return 'cp'. Factory::getConfig()->get('module_id') .'_'. $this->displayName() . '_'. $this->name();
		//$config = CherryPicker::contextModule()->config();
		//$id = CherryPicker::contextModule()->id();
		$id = $this->config->get('module_id');
		return 'cp'. $id .'_'. $this->displayName() . '_'. $this->name();
		//return 'cp'. $id .'_'. $this->displayName() . '_cf_'. $this->customfield->id();
	}

	public function showValueText() {
		return true;
	}

	public function showValueImage() {
		return false;
	}

	public function option($name, $default = false) {
		if ( isset($this->options[$name]) ) return $this->options[$name];
		return $default;
	}

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

	public function removeValueUrl($value) {
		return $this->customfield->removeValueUrl($value);
	}

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

	public function availableValues() {
		if ($this->availableValues) return $this->availableValues;

		$model = $this->customfield;
		//$config = $this->config;
		$type = $this->type();
		$show_empty_values = $this->options['show_empty_values'];
		$sort = $this->options['sort'];
		$selecttype = $this->options['selecttype'];
		$withCount = $this->options['show_count'];
		$limit = 0;
		$seemore_ajax = 0;

		if ($type == 'select') {
			$url = false;
		} else if ($type == 'trackbar') {
			$url = false;
			$withCount = false;
			$show_empty_values = true;
		} else {
			$url = ($type == 'checkbox') ? false : true;
			// todo seemore
			//$task = JRequest::getVar('task', '');
			$display = JRequest::getVar('display', '');
			$seemore_ajax = ($this->options['hide'] == CP_HIDE_SEEMORE
				&& $this->options['seemore_size'] !== ''
				&& $this->options['seemore_ajax']
				&& $display != 'seemore');
				//&& $config->get('ajax_request') == false);

			// increase by 1 to see later whether there is an actual need
			// to show See more.. prompt
			// todo
			if ($seemore_ajax) // && not currently loading with ajax
				$limit = $this->options['seemore_size'] + 1;
		}

		$selectedValues = $model->selectedValues();
		$availableValues = $model->availableValues($withCount, $limit, $url, $selecttype, $sort);
		if ($show_empty_values) {
			$only_submodules = array("category" => true, "shopper" => true);
			$availableValuesAll = $model->availableValues(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']);
					$new['count'] = 0;
					if ($url)
						$new['url'] = (in_array($valueA['name'], $selectedValues)) ?
							$model->removeValueUrl($valueA['name']) : '';
					array_splice($availableValues, $i, 0, array($new));
				}
			}
		}

	//	foreach ($availableValues as &$value) {
	//		$value['alias'] = $value['name'];
	//		$value['name'] = $model->valueTitle($value['name']);
	//	}
	//	unset($value); // referenced last value must be unset

		$remainingValues = array_map(function($v) {
			return $v['alias'];
		}, $selectedValues);
		foreach ($availableValues as &$value)
			if (( $pos = array_search($value['name'], $remainingValues) ) !== false) {
				$value['selected'] = true;
				array_splice($remainingValues, $pos, 1);
			} else {
				$value['selected'] = false;
			}
		unset($value);

		//$selectedValues = $this->customfield->selectedValues();
		if ($this->options['selected_values_ontop'] && $selectedValues
			&& $type != 'trackbar')
		{
			$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;
				}
			if ($seemore_ajax)
				//foreach ($selectedValues as $value) {
				foreach ($remainingValues as $value) {
					$new = array(
						"name" => $value,
						"alias" => $value,
						"count" => '',
						"selected" => true
					);
					if ($url)
						$new['url'] = $this->customfield->removeValueUrl($new);
					$selected[] = $new;

				}

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

		$this->availableValues = $availableValues;

		return $availableValues;
	}

	public function searchMode() {
		$type = $this->type();
		if ($type == 'trackbar') {
			switch ($this->options['trackbar']) {
				case 'oneslider_exact':  return CP_SEARCHMODE_DEFAULT;
				case 'oneslider_lt':     return CP_SEARCHMODE_LT;
				case 'twosliders':       return CP_SEARCHMODE_RANGE;
			}
		} else if ($type == 'text') {
			return CP_SEARCHMODE_TEXT;
		}
		return CP_SEARCHMODE_DEFAULT;
	}

}
