# Model store Images for products, categories etc
class Image < ApplicationRecord
  belongs_to :imageable, polymorphic: true
  has_attached_file :image,
                    path: ':rails_root/public/images/:id/:style/'\
                    ':id_:slugged:dotextension',
                    url: '/images/:id/:style/:id_:slugged:dotextension',
                    styles: {
                      home: '129x129',
                      small: '45x45',
                      medium: '80x80',
                      large: '260x338',
                      thickbox: '600x600'
                    }
  # before_post_process :rename_file
  validates_attachment_content_type :image, content_type: /\Aimage/
  validates_attachment_file_name :image, matches: [/png\z/, /jpe?g\z/, /PNG\z/, /JPE?G\z/]
  do_not_validate_attachment_file_type :image
  scope :by_image_type, ->(type) { where(imageable_type: type) }
  scope :by_position_desc, -> { order(position: :desc) }
  scope :by_position_asc, -> { order(position: :asc) }

  Paperclip.interpolates :slugged do |attachment, _style|
    if attachment.instance.imageable.has_attribute?(:slug)
      attachment.instance.imageable.slug
    else
      't'
    end
  end

  def change_filename(old_name, new_name)
    (image.styles.keys + [:original]).each do |style|
      f1 = img_file_name(old_name)
      f2 = img_file_name(new_name)
      path = image.path(style).sub(f2, f1)
      FileUtils.move(path, File.join(File.dirname(path), f2))
    end
  end

  private

  def img_file_name(oname)
    "#{id}_#{oname}.#{image_file_name.split('.')[-1]}"
  end
end
