<?php namespace ProcessWire;

/**
 * An Inputfield for handling single line "text" form inputs
 * 
 * @property string $type Input type (typically "text")
 * @property int $size Size of input or 0 for full width
 * @property int $maxlength Maximum length of value
 * @property string $placeholder Placeholder attribute text
 * @property string $pattern HTML5 pattern attribute
 * @property string $initValue Optional initial/default value
 * @property bool $stripTags Should HTML tags be stripped from value?
 * @property bool $useLanguages When combined with multi-language support, setting this to true will provide one input per language. Get/set each language value with the "value[languageID]" property, and just "value" for default language. 
 * @property bool|int $requiredAttr When combined with "required" option, this also makes it use the HTML5 "required" attribute. (default=false)
 * 
 *
 */
class InputfieldText extends Inputfield {

	const defaultMaxlength = 2048; 

	public static function getModuleInfo() {
		return array(
			'title' => __('Text', __FILE__), // Module Title
			'summary' => __('Single line of text', __FILE__), // Module Summary
			'version' => 105,
			'permanent' => true, 
			);
	}

	public function __construct() {
		parent::__construct();
		$this->setAttribute('type', 'text'); 
		$this->setAttribute('size', 0); 
		$this->setAttribute('maxlength', self::defaultMaxlength); 
		$this->setAttribute('placeholder', '');
		$this->setAttribute('pattern', '');
		$this->set('requiredAttr', 0);
		$this->set('initValue', ''); // optional initial value
		$this->set('stripTags', false); // strip tags from input?
	}

	public function ___render() {
		$out = "\n<input " . $this->getAttributesString() . " />"; 
		return $out; 
	}

	public function getAttributes() {
		$attrs = parent::getAttributes();
		if(empty($attrs['size'])) {
			unset($attrs['size']); 
			$attrs['class'] = (empty($attrs['class']) ? '' : $attrs['class'] . ' ') . 'InputfieldMaxWidth';
		}
		if(!strlen($attrs['value']) && $this->initValue) {
			$attrs['value'] = $this->initValue; 
		}

		if($this->required && $this->requiredAttr && !$this->getSetting('showIf') && !$this->getSetting('requiredIf')) {
			$attrs['required'] = 'required';
		}

		return $attrs; 
	}

	public function setAttribute($key, $value) {

		if($key == 'maxlength' && ((int) $value) < 1) $value = self::defaultMaxlength; // blank string prevents a maxlength='0' attribute
		if($key == 'value') $value = $this->setAttributeValue($value); 

		return parent::setAttribute($key, $value); 
	}

	protected function setAttributeValue($value) {
		if($this->maxlength) { 
			$value = $this->wire('sanitizer')->text($value, array(
				'maxLength' => $this->maxlength, 
				'maxBytes' => $this->maxlength*3, 
				'stripTags' => false,
				)); 
		}
		if($this->stripTags) $value = strip_tags($value);

		return $value; 
	}

	public function ___processInput(WireInputData $input) {
		parent::___processInput($input);

		$value = $this->attr('value');
		if($this->pattern && strlen($value)) {
			$regex = '#' . str_replace('#', '\#', $this->pattern) . '#'; // add delimeters
			if(!preg_match($regex, $value)) $this->error($this->_('Does not match required pattern')); 
		}

		return $this;
	}

	public function ___getConfigInputfields() {
		
		$inputfields = parent::___getConfigInputfields();
		
		$required = $inputfields->getChildByName('required');
		
		if($required) {
			$required->set('columnWidth', 50);
			$field = $this->modules->get('InputfieldCheckbox');
			$field->attr('name', 'requiredAttr');
			$field->label = $this->_('Also use HTML5 “required” attribute?');
			$field->showIf = "required=1, showIf='', requiredIf=''";
			$field->description = $this->_('Use only on fields *always* visible to the user.');
			$field->icon = 'html5';
			$field->columnWidth = 50;
			if($this->requiredAttr) $field->attr('checked', 'checked');
			$required->getParent()->insertAfter($field, $required);
		}

		$field = $this->modules->get('InputfieldInteger');
		$field->setAttribute('name', 'size'); 
		$field->label = $this->_('Size');
		$field->setAttribute('value', $this->attr('size') > 0 ? $this->attr('size') : 0); 
		$field->setAttribute('size', 4); 
		$field->description = $this->_('The displayed width of this field (in characters). Set to 0 for full width.'); 
		$field->collapsed = Inputfield::collapsedYes;
		$inputfields->append($field);

		$field = $this->modules->get('InputfieldInteger');
		$field->setAttribute('name', 'maxlength'); 
		$field->label = $this->_('Maxlength');
		$field->setAttribute('value', $this->attr('maxlength')); 
		$field->setAttribute('size', 6); 
		$field->description = $this->_('The maximum length (in characters) that are allowed by this field.'); 
		$field->collapsed = Inputfield::collapsedYes;	
		$inputfields->append($field);

		$field = $this->modules->get('InputfieldCheckbox'); 
		$field->attr('name', 'stripTags'); 
		$field->label = $this->_('Strip Tags'); 
		$field->description = $this->_('When checked, any HTML tags will be stripped from the input when the form is processed.'); 
		$field->notes = $this->_('This is recommended if the field does not need to support HTML in it.'); 
		$field->attr('value', 1);
		if($this->stripTags) $field->attr('checked', 'checked');
			else $field->collapsed = Inputfield::collapsedYes;
		$inputfields->append($field); 

		$field = $this->modules->get('InputfieldText');
		$field->setAttribute('name', 'placeholder'); 
		$field->label = $this->_('Placeholder Text');
		$field->setAttribute('value', $this->attr('placeholder')); 
		$field->description = $this->_('Optional placeholder phrase of text that appears in the field when blank.'); 
		$field->collapsed = Inputfield::collapsedBlank;
		$inputfields->append($field);

		$field = $this->modules->get('InputfieldText');
		$field->setAttribute('name', 'pattern'); 
		$field->label = $this->_('Pattern');
		$field->setAttribute('value', $this->attr('pattern')); 
		$field->description = $this->_('Optional regular expression pattern to require in the input. This is used both client side (HTML5 pattern attribute) and server side for validation. Be sure to provide an example of the required pattern in your field description.'); // Pattern description
		$field->notes = $this->_('See [html5pattern.com](http://html5pattern.com) for examples of patterns you can use and create.'); // Pattern notes
		$field->collapsed = Inputfield::collapsedBlank;
		$inputfields->append($field);

		if($this->hasFieldtype === false) { 
			$field = $this->modules->get('InputfieldText');
			$field->setAttribute('name', 'initValue'); 
			$field->label = $this->_('Initial Value');
			$field->description = $this->_('Optional initial/default value pre-populated for the user.'); 
			$field->setAttribute('value', $this->initValue); 
			$field->collapsed = Inputfield::collapsedBlank; 
			$inputfields->append($field);
		}

		return $inputfields; 
	}
	
	public function ___getConfigAllowContext($field) {
		$a = array('initValue', 'pattern', 'placeholder', 'maxlength'); 
		return array_merge(parent::___getConfigAllowContext($field), $a); 
	}
	


	
}
