<?php
/**
 * @package     Redcore
 * @subpackage  HTML
 *
 * @copyright   Copyright (C) 2008 - 2020 redWEB.dk. All rights reserved.
 * @license     GNU General Public License version 2 or later, see LICENSE.
 */

defined('JPATH_PLATFORM') or die;

use Joomla\Registry\Registry;

/**
 * Searchtools filter system
 *
 * @package     Redcore
 * @subpackage  HTML
 * @since       3.2
 */
abstract class JHtmlRsearchtools
{
	/**
	 * Extension name to use in the asset calls
	 * Basically the media/com_xxxxx folder to use
	 */
	const EXTENSION = 'redcore';

	/**
	 * @var    array  Array containing information for loaded files
	 * @since  3.2
	 */
	protected static $loaded = array();

	/**
	 * Load the main Searchtools libraries
	 *
	 * @param   mixed  $debug  Is debugging mode on? [optional]
	 *
	 * @return  void
	 *
	 * @since   3.2
	 */
	public static function main($debug = null)
	{
		// Only load once
		if (empty(static::$loaded[__METHOD__]))
		{
			// Requires jQuery but allows to skip its loading
			if ($loadJquery = (!isset($options['loadJquery']) || $options['loadJquery'] != 0))
			{
				RHtml::_('rjquery.framework');
			}

			// Load the jQuery plugin && CSS
			RHelperAsset::load('lib/jquery-searchtools/jquery.searchtools.min.css', static::EXTENSION);
			RHelperAsset::load('lib/jquery-searchtools/jquery.searchtools.min.js', static::EXTENSION);

			static::$loaded[__METHOD__] = true;
		}

		return;
	}

	/**
	 * Load searchtools for a specific form
	 *
	 * @param   mixed  $selector  Is debugging mode on? [optional]
	 * @param   array  $options   Optional array of parameters for search tools
	 *
	 * @return  void
	 *
	 * @since   3.2
	 */
	public static function form($selector = '.js-stools-form', $options = array())
	{
		$sig = md5(serialize(array($selector, $options)));

		// Only load once
		if (!isset(static::$loaded[__METHOD__][$sig]))
		{
			// Include Bootstrap framework
			static::main();

			// Add the form selector to the search tools options
			$options['formSelector'] = $selector;

			// Generate options with default values
			$options = static::options2Jregistry($options);

			$doc = JFactory::getDocument();
			$script = "
				(function($){
					$(document).ready(function() {
						$('" . $selector . "').searchtools(
							" . $options->toString() . "
						);
					});
				})(jQuery);
			";
			$doc->addScriptDeclaration($script);

			static::$loaded[__METHOD__][$sig] = true;
		}

		return;
	}

	/**
	 * Add javascript support for Bootstrap alerts
	 *
	 * @param   array  $options  Optional settings array
	 *
	 * @return  void
	 *
	 * @since   3.2
	 */
	public static function grid($options = array())
	{
		// Default form name
		if (!isset($options['formName']))
		{
			$options['formName'] = 'adminForm';
		}

		// Only load once
		if (isset(static::$loaded[__METHOD__][$options['formName']]))
		{
			return;
		}

		// If no debugging value is set, use the configuration setting
		if (!isset($options['debug']))
		{
			$config = JFactory::getConfig();
			$options['debug'] = (boolean) $config->get('debug');
		}

		// Include main searchtools framework
		static::main($options['debug']);

		// Attach the popover to the document
		JFactory::getDocument()->addScriptDeclaration(
			"(function($){
				$(document).ready(function() {
					$('#" . $options['formName'] . "').stoolsGrid(" . json_encode($options) . ");
				});
			})(jQuery);
			"
		);

		static::$loaded[__METHOD__][$options['formName']] = true;

		return;
	}

	/**
	 * Function to receive & pre-process javascript options
	 *
	 * @param   mixed  $options  Associative array/JRegistry object with options
	 *
	 * @return  JRegistry        Options converted to JRegistry object
	 */
	private static function options2Jregistry($options)
	{
		// Support options array
		if (is_array($options))
		{
			$options = new JRegistry($options);
		}

		if (!($options instanceof Jregistry))
		{
			$options = new JRegistry;
		}

		return $options;
	}

	/**
	 * Method to sort a column in a grid
	 *
	 * @param   string  $title          The link title
	 * @param   string  $order          The order field for the column
	 * @param   string  $direction      The current direction
	 * @param   mixed   $selected       The selected ordering
	 * @param   string  $task           An optional task override
	 * @param   string  $new_direction  An optional direction for the new column
	 * @param   string  $tip            An optional text shown as tooltip title instead of $title
	 * @param   string  $icon           Icon to show
	 * @param   string  $formName       Name of the form to submit
	 *
	 * @return  string
	 */
	public static function sort($title, $order, $direction = 'asc', $selected = 0, $task = null, $new_direction = 'asc',
		$tip = '', $icon = null, $formName = 'adminForm')
	{
		// Include main searchtools framework
		static::main();

		$direction = strtolower($direction);
		$orderIcons = array('icon-chevron-up', 'icon-chevron-down');
		$index = (int) ($direction == 'desc');

		if ($order != $selected)
		{
			$direction = $new_direction;
		}
		else
		{
			$direction = ($direction == 'desc') ? 'asc' : 'desc';
		}

		// Create an object to pass it to the layouts
		$data            = new stdClass;
		$data->order     = $order;
		$data->direction = $direction;
		$data->selected  = $selected;
		$data->task      = $task;
		$data->tip       = $tip;
		$data->title     = $title;
		$data->orderIcon = $orderIcons[$index];
		$data->icon      = $icon;
		$data->formName  = $formName;

		return RLayoutHelper::render('searchtools.grid.sort', $data);
	}
}
