<?php
namespace Modules\Documents\ImportedDocuments\Webservice\Model\ExecOperation;

/**
 * General class for the authenticate operation
 *
 */
class Authenticate extends GeneralAbstract
{
	/**
	 * The returned token used later for authentication.
	 * @var String
	 */
	protected $sessionToken = NULL;

	/**
	 * Skip the checking of the session token.
	 * {@inheritDoc}
	 * @see \Modules\Documents\ImportedDocuments\Webservice\Model\ExecOperation\GeneralAbstract::checkAuth()
	 */
	protected function checkAuth()
	{ }

	/**
	 * (non-PHPdoc) Checks if username and token are valid
	 * @see \Modules\Documents\ImportedDocuments\Webservice\Model\ExecOperation\GeneralAbstract::checkRequest()
	 */
	protected function checkRequest()
	{
		// username and authToken must be set
		if (!$this->request->username || !$this->request->authToken) {
			throw new \RuntimeException(sprintf('Username and authToken must be set for operation `%s`.', stripClassNamespace(get_class($this))));
		}

		// check if username and authToken are valid
		$importedDocumentSystemsObj = new \App\EntityList\ImportedDocumentsSystems();
		$importedDocumentSystemsObj->setFilter('username', '=', $this->request->username);
		$importedDocumentSystemsObj->setFilter('token', '=', htmlClean($this->request->authToken));

		$importedDocumentSystemsList = $importedDocumentSystemsObj->exportRecords();

		if (!count($importedDocumentSystemsList)) {
			throw new \RuntimeException(sprintf('Username or authToken are invalid for operation `%s`.', stripClassNamespace(get_class($this))));
		}

		if (count($importedDocumentSystemsList) != 1) {
			throw new \RuntimeException("We found more than one system associated with the username and authToken from request");
		}
	}

	/**
	 * Checks the auth token and if everything is ok, it returns the session token.
	 * {@inheritDoc}
	 * @see \Modules\Documents\ImportedDocuments\Webservice\Model\ExecOperation\GeneralAbstract::executeRequestedOperation()
	 */
	protected function executeRequestedOperation()
	{

		try {
			$sessionTokenObject = new \Modules\Documents\ImportedDocuments\Webservice\Model\SessionToken($this->request->username);
			$newSessionToken = $sessionTokenObject->getSessionToken();
		}
		catch (\Modules\Documents\ImportedDocuments\Webservice\Model\SessionTokenException $ex) {
			\Engine\Os::sleep(\Engine\RandomGenerator::randomFloat(1, 2));
			throw new \RuntimeException($ex->getMessage());
		}

		$this->sessionToken = $newSessionToken;
	}

	/**
	 * Returns the session token
	 * @return string
	 */
	public function getSessionToken()
	{
		return $this->sessionToken;
	}

}