#require 'elasticsearch/model'


class VideoFile < ActiveRecord::Base
  #searchkick
  # include Elasticsearch::Model
  # include Elasticsearch::Model::Callbacks
  
	has_many :animal_animalables, :as => :animalable
	has_many :animals, :through => :animal_animalables 
  
	has_many :category_categoryables, :as => :categoryable
	has_many :categories, :through => :category_categoryables 
  
  
  belongs_to :video_folder
  belongs_to :image_file
  belongs_to :investigation_cat
  
  has_many :video_file_langs, :dependent => :destroy
  accepts_nested_attributes_for :video_file_langs
  
  
  scope :recents, -> {where(:public => true).order("video_files.position ASC, video_files.created_at DESC")}
  
  scope :lang, lambda { |lang|
    if lang == "fr"
      where(:fr => true)
    else
      where(:en => true)
    end
      
      
  }
  
  
  
  
  def generate_token()
    begin
      self[:token] = SecureRandom.urlsafe_base64
    end while DataFile.exists?(:token => self[:token])
  end
  
  before_create { generate_token() }
  
  mount_uploader :poster, ImageUploader
  mount_uploader :mpg, VideoUploader
  mount_uploader :ogg, VideoUploader
  mount_uploader :webm, VideoUploader
  
  def lang(locale)
    self.video_file_langs.find_by_lang_site_id(LangSite.find_by_slug(locale).id)
  end
  
  
  
  #after_update do
  #  logger.debug ["Updating document... ",  __elasticsearch__.delete_document, __elasticsearch__.index_document].join

#  end
  
  def search_data
    { 
      title: video_file_langs.map(&:title),
      description: video_file_langs.map(&:description),
      category_names: (categories.map(&:name)),
      category_ids: (categories.map(&:id)),
      animals_names: (animals.map(&:name)),
      animals_ids: (animals.map(&:id)),
      document: "video",
      created_at: created_at
      
    }
  end
	

  def as_indexed_json(options={})
    self.as_json(
      include: { video_file_langs: { only: [:title, :description]}
               })
  end
    
end

#VideoFile.import(:force => true)
