class PortfolioImage < ActiveRecord::Base
  attr_accessible :description, :photo, :shoot_at, :title, :portfolio_ids

  mount_uploader :photo, ImageUploader
  
  has_many :portfolios, :through => :portfolio_portfolio_images
  has_many :portfolio_portfolio_images
  
  
  scope :after, lambda {|time| {:conditions => ["shoot_at > ?", time]}}
  
  def position(portfolio)
    portfolio.images.after(self.shoot_at).count+1
    
  end
  
  def page(portfolio)
    per_page = portfolio.content_type || 1
    (self.position(portfolio)/(per_page*1.0)).ceil
  end
  
  def width
    self.photo.geometry[:width]
  end
  
  def height
    self.photo.geometry[:height]
  end
  
	def rotate(degrees=90)
		versions = [self.photo.path, self.photo.large.path, self.photo.thumb.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
  
  
  def exif
    
    EXIFR::JPEG.new(self.photo.path)
  end
  
  def ratio
      img = Magick::Image::read(self.photo.path).first
      return ((img.columns*1.00) / (img.rows*1.00))
      
  end
  
  
  before_create do
    if self.exif.date_time
      self.shoot_at = self.exif.date_time
    else
      self.shoot_at = Time.now
    end
      
  end
  
  
end
