# -*- encoding : utf-8 -*-
class DataFile < ActiveRecord::Base
  searchkick
  
  belongs_to :file_folder
  belongs_to :militer_cat
  belongs_to :image_file
  belongs_to :square_image_file, :class_name => "ImageFile"
  
  belongs_to :data_file_category
  
  
	has_many :animal_animalables, :as => :animalable
	has_many :animals, :through => :animal_animalables 
  
	has_many :category_categoryables, :as => :categoryable
	has_many :categories, :through => :category_categoryables 
  
  
  
  
  has_many :download_contents
  
  mount_uploader :file, FileUploader

  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_create { generate_token() }



  def file_type
  
    
    mime = `file --mime -br "#{self.file.path}"`.strip.split(';')[0]
    mime
    
  end

  def abstract_file_name
    self.name
  end

  def abstract_file_name_slug
    self.name.to_slug
  end

  

  def generate_token()
    begin
      self[:token] = SecureRandom.urlsafe_base64
    end while DataFile.exists?(:token => self[:token])
  end
  
  
  def search_data
    { 
      title: title,
      description: long_desc,
      category_names: categories.map(&:name),
      category_ids: categories.map(&:id),
      animals_names: animals.map(&:name),
      animals_ids: animals.map(&:id),
      document: (data_file_category ? data_file_category.name.to_slug : "document"),
      created_at: created_at
    }
  end


end