# -*- encoding : utf-8 -*-
class ImageFile < ActiveRecord::Base
  mount_uploader :file, ImageUploader

  before_save do
    if !self.name?
      self.name = File.basename(self.file.filename, File.extname(self.file.filename)).to_s if self.file?
    end
      
  end
  
  before_validation do 
     if self.tags?
      self.tags = self.tags.gsub(/ +?,/, ',')
      self.tags = self.tags.gsub(/, +?/, ',')
      self.tags = self.tags.gsub(/,/, ', ')
    end

  end
  
  after_save do 
    tags_to_save = self.tags.to_s.split(',')
    tags_to_save.each do |t|
      name = t.to_s.strip
      
      Tag.find_or_create_by_name(t.to_s.strip) if name.size > 0
    end
  end
  
  
  
  def rotate(degrees=90)
    versions = [self.file.path, self.file.large.path, self.file.large.medium.path, self.file.large.medium.small.path, self.file.large.medium.small.thumb.path, self.file.square.path]
    
    versions.each do |v|
      image = Magick::ImageList.new(v)
      image = image.rotate(degrees)
      image.write(v)
    end
    self.updated_at = Time.now
    self.save
  end
end
