class MOdrFile < ApplicationRecord
  belongs_to :m_odr_rep
  belongs_to :m_odr_file_type
  belongs_to :p_customer
  belongs_to :m_odr_place
  belongs_to :m_event
  has_many :m_odr_file_products
  accepts_nested_attributes_for :m_odr_file_products, :allow_destroy => true
  

  mount_uploader :file, OdrUploader
  
  validates :file, :presence => true
  
  
  before_create { generate_token() }
  
  def generate_token()
    begin
      self[:token] = SecureRandom.urlsafe_base64
    end while MOdrFile.exists?(:token => self[:token])
  end
    
  
  
  def rotate(degrees=90)
    versions = [self.file.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




   acts_as_sorting :fields => {
      :id => {:name => "Id", :reorder => true},
      :p_customer => {:name => "Client"},
      :m_odr_file_type => {:name => "Type de document"},
      :admin_ok => {:name => "Décision", :reorder => true},
      :reject_reason => {:name => "Raison du rejet", :reorder => true},
      :reject_reason_description => {:name => "Raison du rejet : commentaire", :reorder => true},
      :actions => {:name => "Actions", :reorder => true},

    }




  
  
end
