# -*- encoding : utf-8 -*-
class ImageFile < ActiveRecord::Base
  mount_uploader :file, ImageUploader
  attr_accessor :origin_n
  before_save do
    
  end
  
  before_validation do 
     if self.tags?
      self.tags = self.tags.gsub(/ +?,/, ',')
      self.tags = self.tags.gsub(/, +?/, ',')
      self.tags = self.tags.gsub(/,/, ', ')
    end
    self.generate_token
  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.square_secure_thumb.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.file.recreate_versions!(:secure, :secure_thumb)
    
    
    self.updated_at = Time.now
    self.save
  end

  protected
  def generate_token
    
    if !self.token_s
      begin
        self.token_s = SecureRandom.hex(5)
      end while ImageFile.exists?(:token_s => self.token_s)
      
    end
  end

end
