<?php
/**
 * @version   $Id: AbstractProtocolBuffersMessage.php 11055 2013-05-31 21:05:36Z btowles $
 * @author    RocketTheme http://www.rockettheme.com
 * @copyright Copyright (C) 2007 - 2013 RocketTheme, LLC
 * @license   http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
 */

/**
 * Class RokUpdater_AbstractProtocolBuffersMessage
 */
abstract class RokUpdater_AbstractProtocolBuffersMessage extends ProtocolBuffers_AbstractMessage
{
	protected $container;

	public function __construct($reader = null)
	{
		$this->container = RokUpdater_ServiceProvider::getInstance();

		parent::__construct($reader); // TODO: Change the autogenerated stub
	}

	/**
	 * Sends the message via post request ['message'] to the url
	 *<version>1.0.0-SNAPSHOT</version>
	 * @param $url
	 * @param the ProtocolBuffers_AbstractMessage class where the request should be encoded
	 *
	 * @throws RokUpdater_Exception
	 * @return String - the return string from the request to the url
	 */
	public function Send($url, &$class = null)
	{
		$override_curl_options = $this->container->curl_options;
		$curl_options          = array();
		if (is_array($override_curl_options)) {
			foreach ($override_curl_options as $option => $setting) {
				if (defined($option)) {
					$curl_options[constant($option)] = $setting;
				}
			}
		}

		$streamsocket_options = $this->container->streamsocket_options;


		try {
			$transport       = ProtocolBuffers_TransportFactory::factory(array(
			                                                                  'curl.options'               => $curl_options,
			                                                                  'streamsocket.options'       => $streamsocket_options,
			                                                                  'http_fallback' => $this->container->auth_http_fallback
			                                                             ));
			$this->_d_string = $transport->request(new RokUpdater_Uri($url), $this->SerializeToString());
			if ($class != null) {
				$class->parseFromString($this->_d_string);
			}
		} catch (ProtocolBuffers_Exception $pe) {
			JLog::add($pe->getMessage(), JLog::ERROR, 'rokupdater');
			if ($pe->getCode() == ProtocolBuffers_TransportFactory::PROTOCOL_BUFFERS_ERROR_NO_VALID_TRANSPORT) {
				$message = JText::_('ROKUPDATER_NO_VALID_TRANSPORT');
			} elseif ($pe->getCode() == ProtocolBuffers_TransportFactory::PROTOCOL_BUFFERS_ERROR_SSL_STREAM_NOT_REGISTERED) {
				$message = JText::_('ROKUPDATER_NO_SSL_REGISTERED');
			}
			throw new RokUpdater_Exception($message);
		} catch (Exception $e) {
			JLog::add(JText::sprintf('PLG_SYSTEM_ROKUPDATER_ERROR_COMM_ERR_LOG', $e->getMessage()), JLog::ERROR, 'rokupdater');
			throw new RokUpdater_Exception('ROKUPDATER_COMMUNICATION_ERROR_OCCURED');
		}
		return $this->_d_string;
	}
}
