# encoding: utf-8
module CarrierWave
  module Uploader
    module Versions
      def store_dir
        "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
      end
    end
  end
end

class CustomGalleryUploader < CarrierWave::Uploader::Base
  # Include RMagick or ImageScience support:
  # include CarrierWave::RMagick
  # include CarrierWave::ImageScience
    include CarrierWave::MiniMagick
  # Choose what kind of storage to use for this uploader:
  # storage :file
  # storage :s3

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end
  def get_org_url
    if have_crop?
        model.file.resized.url
    else
        model.file.url
    end
  end
  def fix_exif_rotation 
    manipulate! do |img|
      img.tap(&:auto_orient)
    end
  end
  # Provide a default URL as a default if there hasn't been a file uploaded:
  # def default_url
  #   "/images/fallback/" + [version_name, "default.png"].compact.join('_')
  # end

  # Process files as they are uploaded:
  # process :scale => [200, 300]
  #
  # def scale(width, height)
  #   # do something
  # end

  # Create different versions of your uploaded files:
  # version :thumb do
  #   process :scale => [50, 50]
  # end
  process :resizer
  process :optimize
  version :resized, :if => :have_crop?  do #backup
    def full_filename(for_file)
        extension = File.extname(super(for_file))
        base_name = super(for_file).split('resized_').join('').chomp(extension)
        base_name + '_resized'+ extension
    end
  end
  version :crop_from_org, :if => :have_crop?  do
    process :crop_it
    def full_filename(for_file)
        super(for_file).split('crop_from_org_').join('')
    end
  end
  version :thumb do
    process :convert => 'png', :if => :transparent?
    process :pad_process => [200,200]
  end
  version :thumb_large do
    process :convert => 'png', :if => :transparent?
    process :pad_process => [600,600]
  end
  version :theater do
    process :limit_process => [1920, 1080]
  end
  version :mobile do
    process :limit_process => [1152, 768]
  end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
# def extension_white_list
#   %w(jpg jpeg gif png)
# end

# Override the filename of the uploaded files:
# def filename
#   "something.jpg" if original_filename
# end
  
#  def manipulate!
#    raise current_path.inspect
#    image = ::MiniMagick::Image.open(current_path)
#    image = yield(image)
#    image.write(current_path)
#    ::MiniMagick::Image.open(current_path)
#  rescue ::MiniMagick::Error, ::MiniMagick::Invalid => e
#    raise CarrierWave::ProcessingError.new("Failed to manipulate with MiniMagick, maybe it is not an image? Original Error: #{e}")
#  end
  def get_w_and_h
    if have_crop?
        img = MiniMagick::Image.open(model.file.resized.path)
    else
        img = MiniMagick::Image.open(model.file.path)
    end
    [img[:width], img[:height]]
  end
  def rotate_ang(angle)
    if have_crop?
      img_path = model.file.resized.path
    else
      img_path = model.file.path
    end
    puts img_path
    img = MiniMagick::Image.open(img_path)
    img.rotate(angle)
    puts img
    img.write(img_path)
  end
  def optimize (*arg)
    manipulate! do |img|
        return img unless img.mime_type.match /image\/jpeg/
        img.strip
        img.combine_options do |c|
            c.quality "90"
            c.depth "24"
            c.interlace "plane"
        end
        img
    end
  end
  private
  def resizer
    size_of_file = size.to_f / (2**20)
    if size_of_file > 5
        img = MiniMagick::Image.open(path)
        img_width = img[:width]
        img_height = img[:height]
        multiple = [img_width/Math.sqrt(size_of_file/5)/1920,img_height/Math.sqrt(size_of_file/5)/1080].max
        if (multiple - multiple.to_i)>0.5
            multiple = multiple.to_i + 0.5
        else
            multiple = multiple.to_i
        end
        resize_to_limit(multiple*1920,multiple*1080)
    else
        manipulate! do |img|
            img
        end
    end
  end
  def limit_process(w,h)
    resize_to_limit(w,h)
  end
  def have_crop?(*arg)
    !(model.custom_album_crops.first.nil?)
  end
  def crop_it
    crops = model.custom_album_crops.first
    x=(crops.crop_x).to_i.abs.to_s
    y=(crops.crop_y).to_i.abs.to_s
    w=crops.crop_w.to_i
    h=crops.crop_h.to_i
    crop_image("#{w}x#{h}+#{x}+#{y}")
  end
  def crop_image(geometry)
    img = MiniMagick::Image.open(model.file.resized.path)
    img.crop(geometry)
    img.write(model.file.crop_from_org.path)
  end  
  def transparent?(*arg)
    now_custom_album = model.custom_album
    now_custom_album.custom_album_colors.first['color']=='transparent' rescue true
  end
  def pad_process (w,h)
    now_custom_album = model.custom_album
    resize_and_pad(w, h, (transparent? ? :transparent : now_custom_album.custom_album_colors.first['color']), (now_custom_album.resize_gravity rescue 'Center'))
  end
end