class AnnoncePhoto < ActiveRecord::Base
  belongs_to :annonce
  
  mount_uploader :file, AnnoncePhotosUploader
  
  
	scope :refused, ->{ where(:enabled => false)}
	    
  
  
	scope :visibles, ->{ where("enabled = 1 and (deleted IS NULL or deleted = 0)")}
	    
  
  after_save do
    annonce_default_photo
  end
  
  after_destroy do
    annonce_default_photo
  end
  
  def annonce_default_photo
    if (!self.annonce.default_photo or self.annonce.default_photo.attributes[:deleted] = true or !self.annonce.default_photo.enabled) and self.annonce.annonce_photos.visibles.first
      self.annonce.default_photo = self.annonce.annonce_photos.visibles.first
      self.annonce.save
    else
      self.annonce.default_photo = nil
      self.annonce.save
    end
    
  end
  
  MODO = {}
  MODO[1] = "Image de taille trop petite"
  MODO[2] = "Présence de texte sur les images"
  MODO[3] = "Image de type interdit"
  MODO[4] = "Image comportant des droits d’auteur"

  
  
  def rotate(degrees=90)
    versions = [self.file.path, self.file.medium.path, self.file.medium.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
