<?php
namespace SPAATG\Helper;

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

use SPAATG\Model\Image\ImageModel as ImageModel;
use SPAATG\Controller\ApiKeyController as ApiKeyController;
use SPAATG\Controller\Optimizer\OptimizeAiController;
use SPAATG\Controller\QuotaController as QuotaController;
use SPAATG\Controller\QueueController as QueueController;
use SPAATG\ShortPixelLogger\ShortPixelLogger as Log;


use SPAATG\Model\AccessModel as AccessModel;
use SPAATG\Model\AiDataModel;

class UiHelper
{

	private static $outputMode = 'admin';

	private static $knowledge_url = 'https://shortpixel.com/knowledge-base/article/common-spaatg-bulk-processing-errors/'; // the URL of all knowledge.

	public static function setOutputHandler($name)
	{
		 	self::$outputMode = $name;
	}

  public static function renderBurgerList($actions, $imageObj)
  {
    $output = "";
    $id = $imageObj->get('id');
    $primary = isset($actions['optimizethumbs']) ? 'button-primary' : '';

    $output .= "<div class='sp-column-actions '>
                    <div class='sp-dropdown'>
                        <button onclick='SPAATG.openImageMenu(event);' class='sp-dropbtn button dashicons dashicons-menu $primary' title='SPAATG Actions'></button>";
    $output .= "<div id='sp-dd-$id' class='sp-dropdown-content'>";

    foreach($actions as $actionName => $actionData)
    {
        $disabled = ! empty($actionData['disabled']);
        $link = ($disabled) ? 'javascript:void(0)' : (($actionData['type'] == 'js') ? 'javascript:' . $actionData['function'] : $actionData['function']);
        $classes = $actionName . ($disabled ? ' disabled' : '');
        $disabledAttrs = $disabled ? " aria-disabled='true' tabindex='-1'" : '';
        $title = isset($actionData['title']) ? " title='" . esc_attr($actionData['title']) . "'" : '';
        $actionAttrs = " data-spaatg-action-id='" . esc_attr($id) . "' data-spaatg-action-name='" . esc_attr($actionName) . "'";

        if (! empty($actionData['ai-action']))
        {
            $actionAttrs .= " data-spaatg-ai-action-id='" . esc_attr($id) . "'";
        }

        $output .= "<a href='" . esc_attr($link) . "' class='" . esc_attr($classes) . "'$title$disabledAttrs$actionAttrs>" . esc_html($actionData['text']) . "</a>";
    }

    $output .= "</div> <!--sp-dropdown-content--> </div> <!--sp-dropdown--> </div> <!--sp-column-actions--> ";
    return $output;
  }

  private static function disableAction($action, $message = null)
  {
      $action['disabled'] = true;
      $action['function'] = 'void(0)';
      $action['title'] = is_null($message)
        ? __('This image is already waiting in queue.', 'shortpixel-ai-alt-text-generator')
        : $message;

      return $action;
  }

  private static function disableActions($actions, $message = null)
  {
      foreach($actions as $actionName => $action)
      {
          $actions[$actionName] = self::disableAction($action, $message);
      }

      return $actions;
  }

  public static function renderSuccessText($imageObj)
  {
    return '';

  }

  public static function getListActions($mediaItem, $aiDataModel = null)
  {
      $list_actions = array();
      $id = $mediaItem->get('id');

		  $keyControl = ApiKeyController::getInstance();
			if (! $keyControl->keyIsVerified())
			{
				return []; // nothing
			}

      $quotaControl = QuotaController::getInstance();

			$access = AccessModel::getInstance();
			if (! $access->imageIsEditable($mediaItem))
			{
				 return [];
			}

      if ($id === 0)
      {
				return [];
      }

      $queueController = new QueueController();
      $isItemInQueue = $queueController->isItemInQueue($mediaItem);

	      if (false === is_null($aiDataModel) && $aiDataModel->isProcessable() && 'media' === $mediaItem->get('type') )
	      {
	         $list_actions['spaatg-generateai'] = self::getAction('spaatg-generateai', $id);
	      }

      if(! $quotaControl->hasQuota())
      {
         $list_actions = array();
      }
      if (true === $isItemInQueue)
      {
          $list_actions = self::disableActions($list_actions);
      }

      return $list_actions;
  }

  public static function getActions($mediaItem)
  {
    $actions = [];
    $id = $mediaItem->get('id');
    $quotaControl = QuotaController::getInstance();
    $queueController = new QueueController();
    $optimizeAiController = OptimizeAiController::getInstance();

		$keyControl = ApiKeyController::getInstance();
		if (! $keyControl->keyIsVerified())
		{
			return []; // nothing
		}

		$access = AccessModel::getInstance();
		if (! $access->imageIsEditable($mediaItem))
		{
			 return [];
		}

		if ($id === 0)
    {
			return [];
    }

    $isItemInQueue = $queueController->isItemInQueue($mediaItem);

    if(! $quotaControl->hasQuota())
    {
       $actions['extendquota'] = self::getAction('extendquota', $id);
       $actions['checkquota'] = self::getAction('checkquota', $id);
    }
    elseif ('media' === $mediaItem->get('type') && true === $optimizeAiController->isAiEnabled())
    {
      $aiDataModel = AiDataModel::getModelByAttachment($id);

      if (false !== $aiDataModel && $aiDataModel->isProcessable())
      {
        $actions['spaatg-generateai'] = self::getAction('spaatg-generateai', $id);
      }
    }

    if (true === $isItemInQueue)
    {
        $actions = self::disableActions($actions);
    }

    return $actions;
  }

  public static function getStatusText($mediaItem)
  {
    $keyControl = ApiKeyController::getInstance();
    $queueController = new QueueController();

    $text = '';

		$access = AccessModel::getInstance();

    if (! $keyControl->keyIsVerified())
    {
      $text = __('Invalid API Key. <a href="options-general.php?page=spaatg-settings">Check your Settings</a>','shortpixel-ai-alt-text-generator');
    }
		elseif ($mediaItem->get('id') === 0)
		{
       $text = __('This media item could not be loaded.', 'shortpixel-ai-alt-text-generator');
    }
    elseif (! $mediaItem->exists())
    {
       $text = __('File does not exist.','shortpixel-ai-alt-text-generator');
    }
    elseif ($mediaItem->getMeta('status') < 0)
    {
      $text = $mediaItem->getMeta('errorMessage');
    }
    elseif( $queueController->isItemInQueue($mediaItem) === true)
		{
			 $text = '<p>' . __('This item is waiting for AI SEO generation', 'shortpixel-ai-alt-text-generator') . '</p>';
		}

    return $text;
  }

  public static function getExifDisplayValues($exif)
  {
      if (! is_numeric($exif) || $exif < 0 ||$exif > 7 )
      {
         return false;
      }

      $removed = ($exif % 2 == 0) ? true : false;
      $seo = ($exif >= 2 && $exif <= 5) ? true : false;
      $ai = ($exif >= 2 & $exif <= 3) ? true : false;

      // 0 and 1 options are classic, without ai settings
      if ($exif <= 1)
      {
        $ai = $seo = null;
      }


      $status = [
        'removed' => $removed,
        'ai' => $seo,
        'seo' => $ai,
      ];


      /* translators: %s: EXIF status. */
      $mainline =  sprintf(__('Exif: %s', 'shortpixel-ai-alt-text-generator'), ($removed) ? __('Removed', 'shortpixel-ai-alt-text-generator') : __('Kept', 'shortpixel-ai-alt-text-generator'));

      if (! is_null($ai))
      {
         /* translators: %s: AI usage status. */
         $mainline .=  sprintf(__(', AI %s ', 'shortpixel-ai-alt-text-generator'), ($ai) ? __('Allowed', 'shortpixel-ai-alt-text-generator') : __('Denied', 'shortpixel-ai-alt-text-generator'));
         /* translators: %s: SEO indexing status. */
         $mainline .=  sprintf(__(', SEO %s', 'shortpixel-ai-alt-text-generator'), ($seo) ? __('Allowed', 'shortpixel-ai-alt-text-generator') : __('Denied', 'shortpixel-ai-alt-text-generator'));
      }

      $status['line']  = $mainline;

      return $status;

  }

  // Defines all possible actions in the Ui
  public static function getAction($name, $id, $args = array())
  {
     $action = array('function' => '', 'type' => '', 'text' => '', 'display' => '');
     $keyControl = ApiKeyController::getInstance();

	     $disabled = ! empty($args['disabled']);

	    switch($name)
	    {
	     case 'spaatg-generateai':
	      $action['function'] = 'window.SPAATGProcessor.screen.RequestAlt(' . $id . ')';
	      $action['type'] = 'js';
      $action['text'] = __('Generate AI SEO','shortpixel-ai-alt-text-generator');
      $action['display'] = 'button';
      $action['ai-action'] = true;
      break; 
     case 'extendquota':
        $action['function'] = 'https://shortpixel.com/login/'. $keyControl->getKeyForDisplay();
        $action['type'] = 'button';
        $action['text'] = __('Extend Quota','shortpixel-ai-alt-text-generator');
        $action['display'] = 'button';
     break;
     case 'checkquota':
        $action['function'] = 'SPAATG.checkQuota()';
        $action['type'] = 'js';
        $action['display'] = 'button';
        $action['text'] = __('Check&nbsp;&nbsp;Quota','shortpixel-ai-alt-text-generator');
     break;
   }

   if (true === $disabled)
   {
      $action = self::disableAction($action, isset($args['disabled_message']) ? $args['disabled_message'] : null);
   }

   return $action;
  }

	public static function getConvertErrorReason($error)
	{
		switch($error)
		{
			case -1: //ERROR_LIBRARY:
				$reason = __('PNG Library is not present or not working', 'shortpixel-ai-alt-text-generator');
			break;
			case -2: //ERROR_PATHFAIL:
				$reason = __('Could not create path', 'shortpixel-ai-alt-text-generator');
			break;
			case -3: //ERROR_RESULTLARGER:
				$reason  = __('Result file is larger','shortpixel-ai-alt-text-generator');
			break;
			case -4: // ERROR_WRITEERROR
				$reason = __('Could not write result file', 'shortpixel-ai-alt-text-generator');
			break;
				case -6:  // ERROR_TRANSPARENT
				$reason = __('Image is transparent', 'shortpixel-ai-alt-text-generator');
			break;
			default:
				/* translators: %s: conversion error code. */
				$reason = sprintf(__('Unknown error %s', 'shortpixel-ai-alt-text-generator'), $error);
			break;
		}


		/* translators: %s: conversion error reason. */
		$message = sprintf(__('Not converted: %s ', 'shortpixel-ai-alt-text-generator'), $reason);
		return $message;
	}

	public static function getKBSearchLink($subject)
	{
			return esc_url(self::$knowledge_url); // . sanitize_text_field($subject)); //the KB search doesn't work anymore
	}

	// @param MediaLibraryModel Object $imageItem
	// @param String $size  Preferred size
		// @param String Preload The preloader tries to guess what the preview might be for a more smooth process.
	public static function findBestPreview($imageItem, $size = 800, $preload = false)
	{
		 	$closestObj = $imageItem;

			// set the standard.
			if ($imageItem->getExtension() == 'pdf') // try not to select non-showable extensions.
				$bestdiff = 0;
			else
				$bestdiff = abs($imageItem->get('width') - $size);

			$thumbnails = $imageItem->get('thumbnails');

			if (! is_array($thumbnails))
			{
				 return $closestObj; // nothing more to do.
			}

			foreach($thumbnails as $thumbnail)
			{
					 if (! $preload && ! $thumbnail->isOptimized())
					 	continue;

					$diff = abs($thumbnail->get('width') - $size);
					if ($diff < $bestdiff)
					{
						 $closestObj = $thumbnail;
						 $bestdiff = $diff;
					}
			}

			return $closestObj;
	}

  public static function formatTS($ts)
  {
      //$format = get_option('date_format') .' @ ' . date_i18n(get_option('time_format');
			if (function_exists('wp_date'))
			{
      	$date = wp_date(get_option('date_format'), $ts);
				$date .= ' @ ' . wp_date(get_option('time_format'), $ts);
			}
			else
			{
      	$date = date_i18n(get_option('date_format'), $ts);
				$date .= ' @ ' . date_i18n(get_option('time_format'), $ts);

			}
      return $date;
  }

  public static function formatBytes($bytes, $precision = 2) {
      $units = array('B', 'KB', 'MB', 'GB', 'TB');

      $bytes = max($bytes, 0);
      $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
      $pow = min($pow, count($units) - 1);

      $bytes /= pow(1024, $pow);

      return number_format_i18n(round($bytes, $precision), $precision) . ' ' . $units[$pow];
  }

	public static function formatNumber($number, $precision = 2)
	{
			global $wp_locale;
			$decimalpoint = isset($wp_locale->number_format['decimal_point']) ? $wp_locale->number_format['decimal_point'] : '.';
			$number =  number_format_i18n( (float) $number, $precision);

 			$hasDecimal = (strpos($number, $decimalpoint) === false) ? false : true;

			// Don't show trailing zeroes if number is a whole unbroken number. -> string comparison because number_format_i18n returns string.
			if ($decimalpoint !== false && $hasDecimal && substr($number, strpos($number, $decimalpoint) + 1) === '00')
			{
				 $number = substr($number, 0, strpos($number, $decimalpoint));
			}
			// Some locale's have no-breaking-space as thousands separator. This doesn't work well in JS / Cron Shell so replace with space.
			$number = str_replace('&nbsp;', ' ', $number);
		  return $number;
	}

	public static function formatDate( $date ) {

	if ( '0000-00-00 00:00:00' === $date->format('Y-m-d ') ) {
			$h_time = '';
	} else {
			$time   = $date->format('U'); //get_post_time( 'G', true, $post, false );
			if ( ( abs( $t_diff = time() - $time ) ) < DAY_IN_SECONDS ) {
					if ( $t_diff < 0 ) {
							/* translators: %s: human readable time difference. */
							$h_time = sprintf( __( '%s from now', 'shortpixel-ai-alt-text-generator' ), human_time_diff( $time ) );
					} else {
							/* translators: %s: human readable time difference. */
							$h_time = sprintf( __( '%s ago', 'shortpixel-ai-alt-text-generator' ), human_time_diff( $time ) );
					}
			} else {
					$h_time = $date->format( 'Y/m/d' );
			}
	}

	return $h_time;
}

	protected static function convertImageTypeName($name, $type)
	{
		if ($type == 'webp')
		{
			$is_double = \wpSPAATG()->env()->useDoubleWebpExtension();
		}
		if ($type == 'avif')
		{
			$is_double = \wpSPAATG()->env()->useDoubleAvifExtension();
		}

		if ($is_double)
		{
			 return $name . '.' . $type;
		}
		else
		{
			 return substr($name, 0, strrpos($name, '.')) . '.' . $type;
		}

	}

  /* Strings on settings page that need to be available for both JS and PHP  */
  public static function getSettingsStrings($name = false)
  {

      $strings = array(
      );

      $exclusion_types = array(
          'name' => __('Image Name', 'shortpixel-ai-alt-text-generator'),
          'path' => __('Image Path', 'shortpixel-ai-alt-text-generator'),
          'size' => __('Image Size', 'shortpixel-ai-alt-text-generator'),
          'filesize' => __('Image File Size', 'shortpixel-ai-alt-text-generator'),
	          'date' => __('Date', 'shortpixel-ai-alt-text-generator'),
      );

      $exclusion_apply = array(
           'all' => __('All', 'shortpixel-ai-alt-text-generator'),
           'only-thumbs' => __('Only Thumbnails', 'shortpixel-ai-alt-text-generator'),
           'only-custom' =>  __('Only Custom Media Images', 'shortpixel-ai-alt-text-generator'),
           'selected-thumbs' => __('Selected Images', 'shortpixel-ai-alt-text-generator'),
      );

      $dashboard_string = [
            'ok' => __('Everything ok', 'shortpixel-ai-alt-text-generator'),
            'warning' => __('Improvement possible', 'shortpixel-ai-alt-text-generator'),
            'alert' => __('Action needed', 'shortpixel-ai-alt-text-generator'),
      ];

      $ai_string = [
	            'imagemodaltitle' => __('Select an image for AI SEO data preview', 'shortpixel-ai-alt-text-generator'),
            'selectimage' => __('Use this image', 'shortpixel-ai-alt-text-generator'),
            'preview_requested' => __('Working on your AI SEO data preview. This may take a while ... ', 'shortpixel-ai-alt-text-generator'),
            'preview_select_required' => __('You must select a test image before generating AI SEO data preview.', 'shortpixel-ai-alt-text-generator'),
      ];

      $strings['exclusion_types'] = $exclusion_types;
      $strings['exclusion_apply'] = $exclusion_apply;
      $strings['dashboard_strings'] = $dashboard_string;
      $strings['ai_strings'] = $ai_string; 

      if ($name !== false && isset($strings[$name]))
      {
         return $strings[$name];
      }

      return $strings;
  }

  public static function getIcon($path, $args = array())
  {
      $defaults = array(

      );

      $icon_url = plugins_url($path, SPAATG_PLUGIN_FILE);

      $attr = ''; 
      if (isset($args['width']))
      {
         $attr .= ' width="' . $args['width'] . '"'; 

      }

      if (isset($args['height']))
      {
         $attr .= ' height="' . $args['height'] . '"';
      }


      $html = sprintf('<img src="%s" class="icon"  %s />', esc_attr($icon_url), $attr);

      return $html;

  }



} // class
