<?php
/**
 * ------------------------------------------------------------------------
 * Plugin JA Content Type
 * ------------------------------------------------------------------------
 * Copyright (C) 2004-2018 J.O.O.M Solutions Co., Ltd. All Rights Reserved.
 * @license - GNU/GPL, http://www.gnu.org/licenses/gpl.html
 * Author: J.O.O.M Solutions Co., Ltd
 * Websites: http://www.joomlart.com - http://www.joomlancers.com
 * ------------------------------------------------------------------------
 */

defined('JPATH_PLATFORM') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Form\FormField;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Component\ComponentHelper;

/**
 * Form Field class for the Joomla CMS.
 * Provides a modal media selector including upload mechanism
 *
 * @package     Joomla.Libraries
 * @subpackage  Form
 * @since       1.6
 */


if (version_compare(JVERSION, '4', '>=')) {
	class JFormFieldModal_Media extends Joomla\CMS\Form\Field\MediaField
	{
		protected $type = 'Modal_Media';

		public function setup(SimpleXMLElement $element, $value, $group = null)
		{
			$result = parent::setup($element, $value, $group);

			if ($result === true) {
				$this->types = 'videos';
			}

			return $result;
		}
	}
} else {
	class JFormFieldModal_Media extends FormField
	{
		/**
		 * The form field type.
		 *
		 * @var    string
		 * @since  1.6
		 */
		protected $type = 'Modal_Media';

		/**
		 * The initialised state of the document object.
		 *
		 * @var    boolean
		 * @since  1.6
		 */
		protected static $initialised = false;

		/**
		 * The authorField.
		 *
		 * @var    string
		 * @since  3.2
		 */
		protected $authorField;

		/**
		 * The asset.
		 *
		 * @var    string
		 * @since  3.2
		 */
		protected $asset;

		/**
		 * The link.
		 *
		 * @var    string
		 * @since  3.2
		 */
		protected $link;

		/**
		 * The authorField.
		 *
		 * @var    string
		 * @since  3.2
		 */
		protected $preview;

		/**
		 * The preview.
		 *
		 * @var    string
		 * @since  3.2
		 */
		protected $directory;

		/**
		 * The previewWidth.
		 *
		 * @var    int
		 * @since  3.2
		 */
		protected $previewWidth;

		/**
		 * The previewHeight.
		 *
		 * @var    int
		 * @since  3.2
		 */
		protected $previewHeight;

		protected $legalExtensions = array();

		/**
		 * Method to get certain otherwise inaccessible properties from the form field object.
		 *
		 * @param   string  $name  The property name for which to the the value.
		 *
		 * @return  mixed  The property value or null.
		 *
		 * @since   3.2
		 */
		public function __get($name)
		{
			switch ($name)
			{
				case 'authorField':
				case 'asset':
				case 'link':
				case 'preview':
				case 'directory':
				case 'previewWidth':
				case 'previewHeight':
				case 'legalExtensions':
					return $this->$name;
			}

			return parent::__get($name);
		}

		/**
		 * Method to set certain otherwise inaccessible properties of the form field object.
		 *
		 * @param   string  $name   The property name for which to the the value.
		 * @param   mixed   $value  The value of the property.
		 *
		 * @return  void
		 *
		 * @since   3.2
		 */
		public function __set($name, $value)
		{
			switch ($name)
			{
				case 'authorField':
				case 'asset':
				case 'link':
				case 'preview':
				case 'directory':
					$this->$name = (string) $value;
					break;

				case 'previewWidth':
				case 'previewHeight':
					$this->$name = (int) $value;
					break;
				case 'legalExtensions':
					$this->$name = (array) $value;
					break;

				default:
					parent::__set($name, $value);
			}
		}

		/**
		 * Method to attach a JForm object to the field.
		 *
		 * @param   SimpleXMLElement  $element  The SimpleXMLElement object representing the <field /> tag for the form field object.
		 * @param   mixed             $value    The form field value to validate.
		 * @param   string            $group    The field name group control value. This acts as as an array container for the field.
		 *                                      For example if the field has name="foo" and the group value is set to "bar" then the
		 *                                      full field name would end up being "bar[foo]".
		 *
		 * @return  boolean  True on success.
		 *
		 * @see 	FormField::setup()
		 * @since   3.2
		 */
		public function setup(SimpleXMLElement $element, $value, $group = null)
		{
			$result = parent::setup($element, $value, $group);

			if ($result == true)
			{
				$assetField = $this->element['asset_field'] ? (string) $this->element['asset_field'] : 'asset_id';

				$this->authorField   = $this->element['created_by_field'] ? (string) $this->element['created_by_field'] : 'created_by';
				$this->asset         = $this->form->getValue($assetField) ? $this->form->getValue($assetField) : (string) $this->element['asset_id'];
				$this->link          = (string) $this->element['link'];
				$this->preview       = (string) $this->element['preview'];
				$this->directory     = (string) $this->element['directory'];
				$this->previewWidth  = isset($this->element['preview_width']) ? (int) $this->element['preview_width'] : 200;
				$this->previewHeight = isset($this->element['preview_height']) ? (int) $this->element['preview_height'] : 200;
				$this->legalExtensions = isset($this->element['legalExtensions']) ? explode(',', $this->element['legalExtensions']) : array();
			}

			if(count($this->legalExtensions)) {
				for($i=0; $i<count($this->legalExtensions); $i++) {
					$this->legalExtensions[$i] = strtolower(trim($this->legalExtensions[$i]));
				}
			}

			return $result;
		}

		/**
		 * Method to get the field input markup for a media selector.
		 * Use attributes to identify specific created_by and asset_id fields
		 *
		 * @return  string  The field input markup.
		 *
		 * @since   1.6
		 */
		protected function getInput()
		{
			$asset = $this->asset;

			if ($asset == '')
			{
				$asset = Factory::getApplication()->input->get('option');
			}

			if (!self::$initialised)
			{
				// Load the modal behavior script.
				HTMLHelper::_('behavior.modal');

				// Include jQuery
				HTMLHelper::_('jquery.framework');

				// Build the script.
				$script = array();
				$script[] = '	function jInsertFieldValue(value, id) {';
				$script[] = '		var $ = jQuery.noConflict();';
				$script[] = '		var old_value = $("#" + id).val();';
				$script[] = '		if (old_value != value) {';
				$script[] = '			var $elem = $("#" + id);';
				$script[] = '			$elem.val(value);';
				$script[] = '			$elem.trigger("change");';
				$script[] = '			if (typeof($elem.get(0).onchange) === "function") {';
				$script[] = '				$elem.get(0).onchange();';
				$script[] = '			}';
				$script[] = '			//jMediaRefreshPreview(id);';
				$script[] = '		}';
				$script[] = '	}';

				// Add the script to the document head.
				Factory::getDocument()->addScriptDeclaration(implode("\n", $script));

				self::$initialised = true;
			}

			$html = array();
			$attr = '';

			// Initialize some field attributes.
			$attr .= !empty($this->class) ? ' class="input-text ' . $this->class . '"' : ' class="input-text"';
			$attr .= !empty($this->size) ? ' size="' . $this->size . '"' : '';

			// Initialize JavaScript field attributes.
			$attr .= !empty($this->onchange) ? ' onchange="' . $this->onchange . '"' : '';

			// The text field.
			$html[] = '<div class="input-prepend input-append">';

			$html[] = '	<input type="text" size="50" name="' . $this->name . '" id="' . $this->id . '" value="'
				. htmlspecialchars($this->value, ENT_COMPAT, 'UTF-8') . '" readonly="readonly"' . $attr . ' />';

			if ($this->value && file_exists(JPATH_ROOT . '/' . $this->value))
			{
				$folder = explode('/', $this->value);
				$folder = array_diff_assoc($folder, explode('/', ComponentHelper::getParams('com_media')->get('image_path', 'images')));
				array_pop($folder);
				$folder = implode('/', $folder);
			}
			elseif (file_exists(JPATH_ROOT . '/' . ComponentHelper::getParams('com_media')->get('image_path', 'images') . '/' . $this->directory))
			{
				$folder = $this->directory;
			}
			else
			{
				$folder = '';
			}

			// The button.
			if ($this->disabled != true)
			{
				HTMLHelper::_('bootstrap.tooltip');

				$html[] = '<a class="modal btn" title="' . Text::_('JLIB_FORM_BUTTON_SELECT') . '" href="'
					. ($this->readonly ? ''
						: ($this->link ? $this->link
							: 'index.php?option=com_ajax&amp;plugin=jacontenttype&amp;view=media&amp;tmpl=component&amp;format=html&amp;asset=' . $asset . '&amp;author='
							. $this->form->getValue($this->authorField)) . '&amp;fieldid=' . $this->id . '&amp;folder=' . $folder)
							. '&amp;filter_exts=mp4,mp4v,mpeg,mov,webm"'
					. ' rel="{handler: \'iframe\', size: {x: 1024, y: 500}}">';
				$html[] = Text::_('JLIB_FORM_BUTTON_SELECT') . '</a><a class="btn hasTooltip" title="' . Text::_('JLIB_FORM_BUTTON_CLEAR') . '" href="#" onclick="';
				$html[] = 'jInsertFieldValue(\'\', \'' . $this->id . '\');';
				$html[] = 'return false;';
				$html[] = '">';
				$html[] = '<i class="icon-remove"></i></a>';
			}

			$html[] = '</div>';

			return implode("\n", $html);
		}
	}
}
