module EasyPatch
  module ThumbnailPatch

    def self.included(base)
      base.extend ClassMethods

      base.class_eval do
        class << self
          alias_method_chain :generate, :easy_extensions
          alias_method_chain :convert_available?, :easy_extensions
        end

      end
    end

    module ClassMethods

      def generate_with_easy_extensions(source, target, size)
        unless File.exists?(target)
          directory = File.dirname(target)
          unless File.exists?(directory)
            FileUtils.mkdir_p directory
          end
          EasyExtensions::ImageProcessing.resize_image_to_fit(source, size, size, {:dst => target, :format => 'JPG', :geometry => "#{size}>x#{size}>"})
        end
        File.exists?(target) ? target : source
      rescue EasyExtensions::ImageProcessing::MissingAdapterException
        source
      end

      def convert_available_with_easy_extensions?
        ::Paperclip.with_imagemagick?
      end

    end
  end
end
EasyExtensions::PatchManager.register_model_patch 'Redmine::Thumbnail', 'EasyPatch::ThumbnailPatch'
