<?php
namespace SPAATG\Controller;

use SPAATG\Controller\Api\RequestManager;

if ( ! defined( 'ABSPATH' ) ) {
 exit; // Exit if accessed directly.
}

use SPAATG\ShortPixelLogger\ShortPixelLogger as Log;

use SPAATG\Model\ResponseModel as ResponseModel;
use SPAATG\Model\Image\ImageModel as ImageModel;
use SPAATG\Controller\Api\ApiController as ApiController;
use SPAATG\Model\Queue\QueueItem;

class ResponseController
{

    protected static $items = array();

		protected static $queueName; // the current queueName.
		protected static $queueType;  // the currrent queueType.
		protected static $queueMaxTries;

		protected static $screenOutput  = 1; // see consts down

		// Some form of issue keeping
			const ISSUE_OPTIMIZED_NOFILE = 12; // Issues with missing files
		const ISSUE_QUEUE_FAILED = 13;  // Issues with enqueueing items ( Queue )
		const ISSUE_FILE_NOTWRITABLE = 20; // Issues with file writing
		const ISSUE_DIRECTORY_NOTWRITABLE = 30; // Issues with directory writing


		const ISSUE_API = 50; // Issues with API - general
		const ISSUE_QUOTA = 100; // Issues with Quota.

		const OUTPUT_MEDIA = 1; // Has context of image, needs simple language
		const OUTPUT_BULK = 2;
		const OUTPUT_CLI = 3;  // Has no context, needs more information


		/** Correlates type of item with the queue being used.  Be aware that usage *outside* the queue system needs to manually set type
		* @param Object QueueObject being used.
		*
		*/
		public static function setQ($q)
		{
			 $queueType = $q->getType();

			 self::$queueName = $q->getQueueName();
			 self::$queueType = $queueType;
			 self::$queueMaxTries = $q->getShortQ()->getOption('retry_limit');

			 if (! isset(self::$items[$queueType]))
			 {
				  self::$items[self::$queueType]  = array();
			 }
		}

		public static function setOutput($output)
		{
				self::$screenOutput = $output;
		}


		public static function getResponseItem($item_id)
		{
				if (is_null(self::$queueType)) // fail-safe
				{
					$itemType = "Unknown";
				}
				else {
					$itemType = self::$queueType;
				}

				if (isset(self::$items[$itemType][$item_id]))
				{
					 $item = self::$items[$itemType][$item_id];
				}
				else {
						$item = new ResponseModel($item_id, $itemType);
				}

				return $item;
		}

		protected static function updateResponseItem($item)
		{
				$itemType = $item->item_type;
			  self::$items[$itemType][$item->item_id] = $item;
		}

		// ?
		//
		public static function addData($item_id, $name, $value = null)
		{
			if (! is_array($name) && ! is_object($name) )
			{
				$data = array($name => $value);
			}
			else {
				$data = $name;
			}

			$item_type = (array_key_exists('item_type', $data)) ? $data['item_type'] : false;
			// If no queue / queue type is set, set it if item type is passed to ResponseController.  For items outside the queue system.
			if ($item_type && is_null(self::$queueType))
			{
				 self::$queueType = $item_type;
			}

			$resp = self::getResponseItem($item_id); // responseModel

			foreach($data as $prop => $val)
			{
					if (property_exists($resp, $prop))
					{

						 $resp->$prop = $val;
					}
					else {
					}

			}
			self::updateResponseItem($resp);
		}


		// This is Deprecated

		public static function formatItem($item_id)
		{
				 $item = self::getResponseItem($item_id); // ResponseMOdel
				 $text = $item->message;

				 if ($item->is_error)
					  $text = self::formatErrorItem($item, $text);
				 else {
						$text = self::formatRegularItem($item, $text);
				 }

				 return $text;
		}

		public static function formatQItem(QueueItem $queueItem)
		{
			$result = $queueItem->result();
			$data = $queueItem->data();
			$imageModel = $queueItem->imageModel;

			$item_id = $queueItem->item_id;

			$responseModel = self::getResponseItem($item_id);

			//if (is_null($responseModel->item_type))
			//{
				 $responseModel->item_type = $imageModel->get('type');
			//}

			foreach($result as $resultName => $resultValue)
			{
				if (property_exists($responseModel, $resultName) && false === is_null($responseModel->$resultName))
				{
					 $responseModel->$resultName = $resultValue;
				}
			}

			self::updateResponseItem($responseModel);

			return self::formatItem($item_id);

		}

		private static function formatErrorItem($item, $text)
		{
			switch($item->issue_type)
			{
				}

			switch($item->fileStatus)
			{
				  case ImageModel::FILE_STATUS_ERROR:
								$item_type = (strtolower($item->item_type) == 'media') ? __('Attachment ID ', 'shortpixel-ai-alt-text-generator') : __('Custom # ', 'shortpixel-ai-alt-text-generator');
								/* translators: 1: item type label, 2: item ID. */
								$text .= sprintf(__('( %1$s %2$d ) ', 'shortpixel-ai-alt-text-generator'), $item_type, $item->item_id);
					break;
			}

			switch($item->apiStatus)
			{
	  case RequestManager::STATUS_FAIL:
				$item_type = (strtolower($item->item_type) == 'media') ? __('Attachment ID ', 'shortpixel-ai-alt-text-generator') : __('Custom # ', 'shortpixel-ai-alt-text-generator');
				/* translators: 1: item type label, 2: item ID. */
				$text .= sprintf(__('( %1$s %2$d ) ', 'shortpixel-ai-alt-text-generator'), $item_type, $item->item_id);
					break;
			}


			if (self::$screenOutput == self::OUTPUT_CLI)
			{
				 $text = '(' . self::$queueName . ' : ' . $item->fileName . ') ' . $text . ' ';
			}

			return $text;
		}

		private static function formatRegularItem($item, $text)
		{

			  if (! $item->is_done && $item->apiStatus == ApiController::STATUS_UNCHANGED)
				{
			/* translators: 1: completed images count, 2: total images count. */
			$text = sprintf(__('Generating AI SEO data - waiting for results (%1$d/%2$d)','shortpixel-ai-alt-text-generator'), $item->images_done, $item->images_total);
				}
				if (! $item->is_done && $item->apiStatus == ApiController::STATUS_ENQUEUED)
				{
		/* translators: 1: completed images count, 2: total images count. */
		$text = sprintf(__('Generating AI SEO data - item has been sent to ShortPixel (%1$d/%2$d)','shortpixel-ai-alt-text-generator'), $item->images_done, $item->images_total);
				}

				switch($item->apiStatus)
				{
					 case RequestManager::STATUS_SUCCESS:
						$text = __('AI SEO data generated', 'shortpixel-ai-alt-text-generator');
					 break;

					 case RequestManager::STATUS_FAIL:
					 case ApiController::ERR_TIMEOUT:
						 if (self::$screenOutput < self::OUTPUT_CLI)
						 {
						 }
					 break;
           case RequestManager::STATUS_NOT_API:
              $action = (property_exists($item, 'action')) ? ucfirst($item->action) : __('Action', 'shortpixel-ai-alt-text-generator');
              $filename = (property_exists($item, 'fileName')) ? $item->fileName : '';
              /* translators: 1: action name, 2: file name. */
              $text = sprintf(__('%1$s completed for %2$s', 'shortpixel-ai-alt-text-generator'), $action, $item->fileName);
           break;
				}

				if (self::$screenOutput == self::OUTPUT_CLI)
				{
					 $text = '(' . self::$queueName . ' : ' . $item->fileName . ') ' . $text . ' ';
           if ($item->tries > 0)
					      /* translators: %d: retry cycle number. */
					      $text .= sprintf(__('(cycle %d)', 'shortpixel-ai-alt-text-generator'), intval($item->tries) );
				}
				return $text;
		}

} // Class
