<?php

class Tag_Label extends Tag
{
	public static $default_format = '%s';
	public static $default_required_format = '<span class="asterix">*</span>%s';

	public $required = false;

	protected $format = NULL;
	protected $required_format = NULL;

	// Note; attributes param can be an array or single string value, this is so we can use
	// implementation like $x = new Tag_Label('My Label', 'my_text_field', 'R') to indicate a required label
	// OR  $x = new Tag_Label('My Label', 'my_text_field', array('R','style'=>'width:21px;') ); to indicate a required label WITH attributes on the tag
	public function __construct($text='Label', $for='', $attributes=NULL)
	{
		// Ensure that the attributes are in their most basic form, an empty array or array of values
		if( !is_array($attributes) && !is_null($attributes))
			$attributes = array($attributes);
		elseif( is_null($attributes) )
			$attributes = array();

		// Determine Required status
		$i = array_search('R', $attributes);
		if( $i !== false )
		{
			unset($attributes[$i]);
			$this->required = true;
		}

		parent::__construct('label', $attributes, TAG_CLOSE);

		$this->text($text); // Automagically sets the tag to end with a completion tag

		if($for) $this->attr('for', $for);
		if( array_key_exists('format', $attributes) )
		{
			$this->setFormat( $attributes['format'] );
			unset($this->attributes['format']);
		}
	}

	// Sets the class specific "global" format string for use within printf statements during the rendering process
	public static function setDefaultFormat($format='%s', $required_format='<span class="asterix">*</span>%s')
	{
		self::$default_format = $format;
		self::$default_required_format = $required_format;
	}

	// Set printf format string for the label output, for this specific instance or the class
	public function setFormat($format='%s', $required_format='<span class="asterix">*</span>%s')
	{
		$this->instance_format = $format;
		$this->instance_required_format = $required_format;
	}

	public function getFormat()
	{
		if( $this->required ) // Required Field
		{
			return (is_null($this->required_format)?self::$default_required_format:$this->required_format);
		}
		else
		{
			return (is_null($this->format)?self::$default_format:$this->format);
		}
	}

	// Override render to provide additional printf formatting on the label text
	public function render($return=false)
	{
		$this->text = sprintf($this->getFormat(), $this->text);
		if( $this->required )
			$this->addClass('required');
		return parent::render($return);
	}

	/** Overrides base functionality to provide additional support for <em> sub-label text */
	public function text($text='')
	{
		if( is_array($text) )
		{
			$label = $text[0];
			for($i=1;$i<count($text);$i++)
				$label .= sprintf('<em>%s</em>',$text[$i]);
		}
		else
		{
			$label = $text;
		}
		$this->text = $label;
	}

}
