class PhotoUploader < CarrierWave::Uploader::Base

  include CarrierWave::ImageOptimizer
  if RbConfig::CONFIG["target_os"] =~ /mswin|mingw|cygwin/i
    include CarrierWave::MiniMagick
  else
    include CarrierWave::RMagick
  end

  def store_dir
    "uploads/#{mounted_as}/#{model.safe_url}"
  end

  def default_url
    "/static/image_default.jpg"
  end

  def filename
    "#{model.safe_url}-#{secure_token}.jpg" if original_filename.present?
  end

  storage :file
  # process :remove_animation

  version :large do
    process convert: :jpg
    process resize_to_limit: [900, 900]
    process optimize: [{ quality: 70 }] # if RUBY_PLATFORM =~ /x86_64-linux/
  end

  version :medium, from_version: :large do
    process resize_to_limit: [600, 600]
  end

  version :thumb, from_version: :medium do
    process resize_to_limit: [100, 100]
  end

  def fix_exif_rotation
    manipulate! do |img|
      img.tap(&:auto_orient!)
    end
  end

  process :fix_exif_rotation # if !RbConfig::CONFIG["target_os"] =~ /mswin|mingw|cygwin/i

  protected

  def secure_token(length=4)
    var = :"@slug"
    model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.hex(length/2))
  end

  def remove_animation
    manipulate! { |image| image.collapse! } if content_type == 'image/gif'
  end

end