<?php

namespace SPAATG\Helper;

use SPAATG\ShortPixelLogger\ShortPixelLogger as Log;


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

// Our newest Tools class
class UtilHelper
{

  public static function shortPixelIsPluginActive($plugin)
  {
    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WordPress core filter name.
    $activePlugins = apply_filters('active_plugins', get_option('active_plugins', array()));
    if (is_multisite()) {
      $activePlugins = array_merge($activePlugins, get_site_option('active_sitewide_plugins'));
    }
    return in_array($plugin, $activePlugins);
  }

  public static function timestampToDB($timestamp)
  {
    return gmdate("Y-m-d H:i:s", $timestamp);
  }

  public static function DBtoTimestamp($date)
  {
    return strtotime($date);
  }

  public static function getWordPressImageSizes()
  {
    global $_wp_additional_image_sizes;

    $sizes_names = get_intermediate_image_sizes();
    $sizes = array();
    foreach ($sizes_names as $size) {
      $sizes[$size]['width'] = intval(get_option("{$size}_size_w"));
      $sizes[$size]['height'] = intval(get_option("{$size}_size_h"));
      $sizes[$size]['crop'] = get_option("{$size}_crop") ? get_option("{$size}_crop") : false;
      $sizes[$size]['nice-name'] = ucfirst($size);
    }
    if (function_exists('wp_get_additional_image_sizes')) {
      $sizes = array_merge($sizes, wp_get_additional_image_sizes());
    } elseif (is_array($_wp_additional_image_sizes)) {
      $sizes = array_merge($sizes, $_wp_additional_image_sizes);
    }

    $sizes = apply_filters('spaatg/settings/image_sizes', $sizes);
    return $sizes;
  }



  // wp_normalize_path doesn't work for windows installs in some situations, so we can use it, but we still want some of the functions.
  public static function spNormalizePath($path)
  {
    $path = preg_replace('|(?<=.)/+|', '/', $path);
    return $path;
  }

  public static function getExifParameter()
  {
    return (\wpSPAATG()->settings()->exif + \wpSPAATG()->settings()->exif_ai);
  }

  // Copy of private https://developer.wordpress.org/reference/functions/_wp_relative_upload_path/
  public static function getRelativeUploadPath($path)
  {
    $new_path = $path;
    $uploads = wp_get_upload_dir();
    if (0 === strpos($new_path, $uploads['basedir'])) {
      $new_path = str_replace($uploads['basedir'], '', $new_path);
      $new_path = ltrim($new_path, '/');
    }
    return $new_path;
  }

  /** Usage: Plug this into array_filter method. 
   * 
   * @return bool 
   */
  public static function arrayFilterNullValues($val)
  {
    return $val !== null;
  }

  public static function validateJSON($json)
  {
    if (!is_string($json)) {
      return false;
    }

    // Try to simpler bail out without checking for the decode.
		if (strpos($json, '{' ) === false && strpos($json, ':') === false)
		{
			return false; 
		}

    if (function_exists('json_validate')) {
      return \json_validate($json);
    }

    json_decode($json);
    return json_last_error() === JSON_ERROR_NONE;
  }

  public static function getExclusions($args = array())
  {
    $defaults = array(
      'filter' => false,
      'thumbname' => null,
      'is_thumbnail' => false,
      'is_custom' => false,
    );

    $args = wp_parse_args($args, $defaults);

    $patterns = \wpSPAATG()->settings()->excludePatterns;
    $matches = array();

    if (false === is_array($patterns)) {
      return array();
    }

    foreach ($patterns as $index => $pattern) {
      if (! isset($pattern['apply'])) {
        $patterns[$index]['apply'] = 'all';
      }

      if (true === $args['filter']) {
        if (true === self::matchExclusion($patterns[$index], $args)) {
          $matches[] = $pattern;
        }
      }
    }

    if (true === $args['filter']) {
      return $matches;
    } else
      return $patterns;
  }

  protected static function matchExclusion($pattern, $options)
  {
    $apply = $pattern['apply'];
    $thumblist = isset($pattern['thumblist']) ? $pattern['thumblist'] : array();
    $bool = false;

    if ($apply === 'all') {
      $bool = true;
    } elseif ($apply == 'only-thumbs' && true === $options['is_thumbnail']) {
      $bool = true;
    } elseif ($apply == 'only-custom' && true === $options['is_custom']) {
      $bool = true;
    } elseif (count($thumblist) > 0 && ! is_null($options['thumbname'])) {
      $thumbname = $options['thumbname'];
      if (in_array($thumbname, $thumblist)) {
        $bool = true;
      }
    }
    return $bool;
  }

  public static function getAiSettings($params = [])
  {
    $settings = \wpSPAATG()->settings(); 

    $defaults = [
    'ai_general_context' => $settings->ai_general_context, 
    'ai_use_post' => $settings->ai_use_post, 
    'ai_gen_alt' => $settings->ai_gen_alt, 
    'ai_gen_caption' => $settings->ai_gen_caption, 
    'ai_gen_description' => $settings->ai_gen_description, 
    'ai_gen_post_title' => $settings->ai_gen_post_title, 
    'ai_filename_prefercurrent' => $settings->ai_filename_prefercurrent,
    'ai_limit_alt_chars' => $settings->ai_limit_alt_chars, 
    'ai_alt_context' => $settings->ai_alt_context, 
    'ai_limit_description_chars' => $settings->ai_limit_description_chars, 
    'ai_description_context' => $settings->ai_description_context, 
    'ai_limit_caption_chars' => $settings->ai_limit_caption_chars, 
    'ai_caption_context' => $settings->ai_caption_context, 
    'ai_limit_post_title_chars' => $settings->ai_limit_post_title_chars, 
    'ai_post_title_context' => $settings->ai_post_title_context, 
    'ai_gen_filename' => $settings->ai_gen_filename, 
    'ai_limit_filename_chars' => $settings->ai_limit_filename_chars, 
    'ai_filename_context' => $settings->ai_filename_context, 
    'ai_use_exif' => $settings->ai_use_exif, 
    'ai_language' => $settings->ai_language,
    'aiPreserve' => $settings->aiPreserve, 
    ];

    $params = wp_parse_args($params, $defaults);

    return $params; 
  }

  public static function convertExclusionFileSizeToBytes($value)
  { 
    return preg_replace_callback('/^\s*(\d+)\s*(?:([kmgt]?)b?)?\s*$/i', function ($m) {
      switch (strtolower($m[2])) {
        case 't': $m[1] *= 1024;
        case 'g': $m[1] *= 1024;
        case 'm': $m[1] *= 1024;
        case 'k': $m[1] *= 1024;
      }
      return $m[1];
    }, $value);

  }

} // class
