class ImageUploader < CarrierWave::Uploader::Base

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

  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}"
  end

  def default_url
    "/static/image_default.jpg"
  end

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

  version :large do
    process :convert => :jpg
    # process :interlace => 'Plane'
    process :fix_exif_rotation
    # process :quality => 70
    process resize_to_fit: [960, 960]
  end

  version :thumb, from_version: :large do
    process :fix_exif_rotation
    process resize_to_fit: [600, 600]
  end

  def interlace(type)
    manipulate! do |img|
      img.interlace(type.to_s)
      img = yield(img) if block_given?
      img
    end
  end

  def quality(percentage)
    manipulate! do |img|
      img.strip!
      img.quality(percentage.to_s)
      img = yield(img) if block_given?
      img
    end
  end

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

  protected

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

end