<?php
namespace ModulesAbstract\ElectronicInvoice\Communicator;

class AbstractCommunicator
{
	/**
	 * The internal logger
	 *
	 * @var \Engine\Logger\GeneralAbstract
	 */
	protected $logger = null;


	public function __construct()
	{
		$this->logger = new \Engine\Logger\Dummy();
	}

	/**
	 * Get the used logger
	 * @return \Engine\Logger\GeneralAbstract
	 */
	public function getLogger()
	{
		return $this->logger;
	}

	/**
	 * Set the internal logger
	 *
	 * @param \Engine\Logger\GeneralAbstract|\Engine\Logger\MultipleLogger $logger
	 * @return $this
	 */
	public function setLogger($logger)
	{
		$this->logger = $logger;

		return $this;
	}

	/**
	 * Create the HTTP transfer object
	 * @return \App\Utils\HttpTransfer\StandardTransferWithErrorHandling
	 */
	protected function createHttpTransferObj()
	{
		$transfer = new \App\Utils\HttpTransfer\StandardTransferWithErrorHandling();
		$transfer->setHeaders([
			'User-Agent: StandardTransferWithErrorHandling',
			'Accept-Language: en',
		]);
		ini_set("default_socket_timeout", 1.5*60);

		return $transfer;
	}

    protected function json_decode($jsonStr)
	{
		$json = \json_decode($jsonStr);
		/**
		 * json_decode has a problem with UTF8 chars, and doesn't support them embedded directly. They have to be escaped in the input data
		 * A workaround would be mb_convert_encoding($value, "UTF-8", "auto"), or iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($value)) but this would remove invalid chars, or replace them with placeholders
		 * Also, json_last_error() has to be checked for more detailed errors regarding the input json
		 */
		$json_last_error_str = null;
		switch (json_last_error()) {
			case JSON_ERROR_NONE:
			break;
			case JSON_ERROR_DEPTH:
				$json_last_error_str = 'JSON_ERROR_DEPTH - Maximum stack depth exceeded';
			break;
			case JSON_ERROR_STATE_MISMATCH:
				$json_last_error_str = 'JSON_ERROR_STATE_MISMATCH - Underflow or the modes mismatch';
			break;
			case JSON_ERROR_CTRL_CHAR:
				$json_last_error_str = 'JSON_ERROR_CTRL_CHAR - Unexpected control character found';
			break;
			case JSON_ERROR_SYNTAX:
				$json_last_error_str = 'JSON_ERROR_SYNTAX - Syntax error, malformed JSON';
			break;
			case JSON_ERROR_UTF8:
				$json_last_error_str = 'JSON_ERROR_UTF8 - Malformed UTF-8 characters, possibly incorrectly encoded';
			break;
			default:
				$json_last_error_str = 'unknown';
			break;
		}

		if ($json_last_error_str) {
			throw new \Exception\Net\Base(sprintf("[%s] Invalid JSON response. Error: %s", __METHOD__, $json_last_error_str));
		}

		return $json;
	}

    /**
	 * Log the request and response.
	 *
	 * @param array $logContext
	 * @param \App\Utils\HttpTransfer\StandardTransferWithErrorHandling $transfer
	 * @return array
	 */
	protected function buildLogContextFromStandardTransferWithErrorHandling(array $logContext, \App\Utils\HttpTransfer\StandardTransferWithErrorHandling $transfer)
	{
		$lastRequest = $transfer->getLastRequest();

		unset($lastRequest['lastResponse']['processedHeaders']);

        // if ($lastRequest['lastResponse']['body']) {
		// 	$logContext['responseJSON'] = new \Engine\Logger\Context\Auto($lastRequest['lastResponse']['body']);
		// }

		// if ($lastRequest['lastRequest']['body']) {
		// 	$logContext['requestJSON'] = new \Engine\Logger\Context\Json(json_decode($lastRequest['lastRequest']['body']));
		// }

		$logContext['getLastRequest'] = new \Engine\Logger\Context\StandardTransferLastRequest($lastRequest);


		return $logContext;
	}


}
