<?php

/**
 * Dynamic image support
 *
 * Upload image thumbnails generated by your theme and
 * plugins that do not register media objects with the media library.
 *
 * @since 3.3.0
 */

namespace wpCloud\StatelessMedia {
  if (!class_exists('wpCloud\StatelessMedia\DynamicImageSupport')) {

    /**
     * Class DynamicImageSupport
     *
     * @package wpCloud\StatelessMedia
     */
    class DynamicImageSupport {
      use Singleton;

      const ID = 'dynamic-image-support';

      public function __construct() {
        // On Google App Engine not working
        if ( apply_filters('wp_stateless_is_app_engine', false) ) {
          return;
        }

        $enabled = ud_get_stateless_media()->get( 'sm.dynamic_image_support', false ) == 'true';

        // Legacy setting
        if (!$enabled) {
          $enabled = get_option('sm_on_fly', false);
        }

        if ($enabled) {
          $this->init_module();
        }
      }

      /**
       * Initialize module
       */
      private function init_module() {
        // Handle any other on fly generated media
        add_filter('image_make_intermediate_size', array($this, 'handle_on_fly'));
      }

      /**
       * Handle images on fly
       * f6a7dfd9 Anton Korotkov, 2 years ago (September 29th, 2015 6:09am)
       * @param $file
       * @return mixed
       */
      public function handle_on_fly($file) {
        $client = ud_get_stateless_media()->get_client();
        $upload_dir = wp_upload_dir();

        $file_path = str_replace(trailingslashit($upload_dir['path']), '', $file);
        $file_info = @getimagesize($file);
        $mimeType = wp_check_filetype($file);

        if ($file_info) {
          $_metadata = array(
            'width'  => $file_info[0],
            'height' => $file_info[1],
            'object-id' => 'unknown', // we really don't know it
            'source-id' => md5($file . ud_get_stateless_media()->get('sm.bucket')),
            'file-hash' => md5($file)
          );
        }

        $client->add_media(apply_filters('sm:item:on_fly:before_add', array_filter(array(
          'name' => $file_path,
          'absolutePath' => wp_normalize_path($file),
          'cacheControl' => apply_filters('sm:item:cacheControl', ud_get_stateless_media()->get_default_cache_control(), $_metadata),
          'contentDisposition' => null,
          'mimeType' => $mimeType['type'],
          'metadata' => $_metadata
        ))));

        return $file;
      }
    }
  }
}
