<?php

class Tag_Field extends Tag
{
	public $label;
	public $field;

	protected static $class_null_string_format = '---'; // Value displayed if the provided "field" is an empty or null string
	protected $instance_null_string_format = NULL;

	// $label - string - will be output as a LABEL tag
	// $tag_object - string||object - if provided as a Tag object, will be rendered, otherwise it will be output as a literal string value
	// $required - bool - obviously determines whether or not the associated label is rendered with a "required" indicator
	public function __construct($label, $tag_object, $required=false)
	{
		$this->attributes = array();
		$this->field = $tag_object;

		if( is_object($label) && get_class($label) == 'Tag_Label' )
			$this->label = $label;
		else
			$this->label = new Tag_Label($label);

		if( is_object($tag_object) )
			$this->label->attr('for', $this->field->attr('id'));

		$this->label->required = $required;
	}

	public function setDefaultNullStringFormat($format)
	{
		self::$class_null_string_format = $format;
	}

	public function setNullStringFormat($format)
	{
		$this->intance_null_string_format = $format;
	}

	public function render($return=false)
	{
		// Setup the template for the layout of the field and label
		$tmpl = '<div class="field">%1$s%2$s</div>'; // Default

		// Special Considerations for labels based on the type of field;
		if( is_object($this->field) && $this->field instanceof Tag )
		{
			switch(get_class($this->field))
			{
				case 'Tag_Textarea':
					$this->label->addClass('textarea');
					break;
			}
		}

		// The structure allows for non-object content such as string values to be shown instead of actual TAG based fields
		if( is_object($this->field) )
		{
			// By default it "should" be a TAG instance

			// Check to see if the required class is needed
			if( $this->field instanceof Tag && $this->label->required )
			{
				$this->field->addClass('required');
				$this->field->attributes["required"] = "required";
			}

			// Render the Tag Object
			$field_markup = $this->field->render(true);
		}
		else
		{
			// Handling of non-object, non-Tag items (literals)
			if( is_null($this->field) || $this->field == '' )
			{
				if( is_null($this->instance_null_string_format) )
				{
					$field_markup = self::$class_null_string_format;
				}
				else
				{
					$field_markup = $this->$instance_null_string_format;
				}
			}
			else
			{
				$div = new Tag('div');
				$div->addClass('input');
				$div->text($this->field);
				$field_markup = $div->render(true); // Assume Literal Value and output it wrapped in a div with class "input" applied
			}
		}

		if($return)
		{
			return sprintf($tmpl, $this->label->render(true), $field_markup);
		}
		else
		{
			printf($tmpl, $this->label->render(true), $field_markup);
		}
	}
}
