# encoding: utf-8
# my smart cropping system
module Paperclip
  class SmartCropTop < Thumbnail
    # for an asked_geometry, we determine what is the best way to crop an image
    # without loosing too much information so we first resize to the best size
    # and then we crop by top
    def transformation_command
      # we try to adjust width so let's see if height will be ok
      resize_w = @target_geometry.width
      resize_h = @target_geometry.width / @current_geometry.aspect
      if resize_h < @target_geometry.height && !@target_geometry.modifier.to_s.index('#')
        # not enough, so we must resize by height
        resize_w = @target_geometry.height * @current_geometry.aspect
        resize_h = @target_geometry.height
      end

      trans = []
      trans << "-resize" << "#{resize_w.to_i}x#{resize_h.to_i}"
      x = ((resize_w - @target_geometry.width) / 2).to_i
      y = 0
      trans << "-crop" << "#{@target_geometry.width.to_i}x#{@target_geometry.height.to_i}+#{x}+#{y}"
      trans << "+repage"
      trans << "-format" << @format.to_s if @format
      trans
    end
  end
end
