<?php

/**
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package fusionLib
 * @copyright Copyright (c) 2007 - 2015 fusionLib. All rights reserved.
 * @link http://fusionlib.com
 */

/**
 * flFormElementFile Class
 *
 * File input form element.
 *
 * @package fusionLib
 */
class flFormElementFile extends flFormElementText {

	/**
	 * True if drawing a styled element else false.
	 *
	 * @var bool
	 */
	protected $styled = true;

	/**
	 * Draw the element.
	 *
	 * @return string The HTML.
	 */
	function render() {
		$html = "<input type=\"file\" id=\"$this->name\" name=\"$this->name\"";
		if($this->maxLength !== null) $html .= " maxlength=\"$this->maxLength\"";
		$html .= $this->attribHTML() . " />\n";

		if($this->styled) {
			$html = '<div class="uploadButton ' . ($this->class ? $this->class : '') .'"><span aria-live="polite">' . __('Choose File', 'fusionLib') . '</span>' . $html . '</div>';
			$this->js = "\$fl('#$this->name').bind('change', function(e) { \$fl(this).parent().find('span').html(\$fl(this).val().split(/(\\\\|\\/)/g).pop()); })\n";
		}

		return $html;
	}

	/**
	 * Enable or disable the styling of the upload button.
	 *
	 * @param bool $styled true if styled, the default, or false for the OS upload button.
	 */
	function styleUpload($styled = true) {
		$this->styled = $styled;
	}

	/**
	 * Test if a file is uploaded.
	 *
	 * @return bool true if a file was uploaded; else false.
	 */
	function fileUploaded() {
		return $this->form->getRequest()->hasFile($this->name);
	}

	/**
	 * Get the error if any for an uploaded file.
	 *
	 * @return int The error code one of flRequest::UPLOAD*
	 */
	function getFileError() {
		return $this->form->getRequest()->getFileError($this->name);
	}

	/**
	 * Get the temporary file name an uploaded file.
	 *
	 * @return string The name of the temporary file or false if the file was not uploaded.
	 */
	function getTmpFileName() {
		return $this->form->getRequest()->getTmpFileName($this->name);
	}

	/**
	 * Get the file name an uploaded file.
	 *
	 * @return string The name of the file or false if the file was not uploaded.
	 */
	function getFileName() {
		return $this->form->getRequest()->getFileName($this->name);
	}

	/**
	 * Move the uploaded file to a permanent location.
	 *
	 * @param string $to The path and name to move the file to.
	 * @param string $default The file to copy as a default if the named file is not available.
	 * @return bool true if the file was moved or false if it failed.
	 */
	function moveTo($to, $default = null) {
		return $this->form->getRequest()->moveUploadedFile($this->name, $to, $default);
	}
}
