<?php

namespace Modules\Utils\ExportData;

/**
 * The mapped websrvice object - contains two methods - GetFile (gets the first file from the queue)
 * and ConfirmFile (confirms the first file from the queue to go to the next one).
 * @author Gabriel
 *
 */
class Ws_ExportFile
{

	/**
	 * Indicates if the security code from the AuthHeader is correct.
	 * @var Boolean
	 */
	private $authenticated=false;

	/**
	 * Populates the internal attribute 'authenticated'.
	 * @param Ws_AuthHeader $auth
	 * @throws \SoapFault
	 */
	public function AuthHeader(Ws_AuthHeader $auth)
	{

		// check if any security code was set
		if (!$auth->securityCode) {
			throw new \SoapFault('102', 'The security code is not set.');
		}

		$this->authenticated = $auth->isValid();

		// if the security code is not okay - throw soap fault
		if (!$this->authenticated) {
			throw new \SoapFault('103', 'The security code is not valid.');
		}

	}

	/**
	 * Returns the
	 * @throws \SoapFault
	 * @return \Modules\Utils\ExportData\Ws_GetFile_Response
	 */
	public function GetFile()
	{

		// avoid DoS
		$this->avoidDos();

		// check if the security code is set and valid
		if (!$this->authenticated) {
			throw new \SoapFault('101', 'The soap header which should contain the security code was not set.');
		}

		// gets the response
		$getFileRs = new Ws_GetFile_Response();

		return $getFileRs;

	}


	/**
	 * Confirms the first file from the queue (first checks if the request data is correct).
	 * @param Ws_ConfirmFile_Request $rq
	 * @throws \SoapFault
	 * @return \Modules\Utils\ExportData\Ws_ConfirmFile_Response
	 */
	public function ConfirmFile(Ws_ConfirmFile_Request $rq)
	{

		// avoid DoS
		$this->avoidDos();

		// check if the security code is set and valid
		if (!$this->authenticated) {
			throw new \SoapFault('101', 'The soap header which should contain the security code was not set.');
		}

		$confirmFileRs = new Ws_ConfirmFile_Response();
		$confirmFileRs->setRequest($rq);
		$confirmFileRs->confirm();
		return $confirmFileRs;

	}


	/**
	 * The method is called from the WS operations in order to sleep for a while to avoid DoS.
	 */
	private function avoidDos()
	{

		// sleep period (in ms)
		$sleepPeriod=rand(0, 1000);
		usleep($sleepPeriod*1000);

	}

}