require 'elasticsearch/model'

class Article < ActiveRecord::Base
  include Elasticsearch::Model
  include Elasticsearch::Model::Callbacks
  
  has_many :question_juridiques
  
  has_many :menu_item_articles
  has_many :menu_items, :through => :menu_item_articles
  
  has_many :comments, :as => :commentable
  
  belongs_to :image_file
  belongs_to :without_text_image_file, :class_name => "ImageFile"
  
  
	
	has_many :blocks, :as => :blockable
	
	belongs_to :category
	has_many :enabled_comments,-> {where(:enabled => true)}, :source => :comments, :as => :commentable
	after_create :after_creation
  
  
  
  has_many :lang_articles, :dependent => :destroy
    
  accepts_nested_attributes_for :lang_articles

	has_many :tag_taggables, :as => :taggable
	has_many :tags, :through => :tag_taggables 
  
  belongs_to :article_author
  
  validates :published_at, :presence => true
  
  attr_accessor :skip_block
  
	
  
  HUMAN_NAME =  "lien vers un article."
  
  def lang(locale)
    self.lang_articles.find_by_lang_site_id(LangSite.find_by_slug(locale).id)
  end
	
	def name
    self.lang_articles.first.title
  end

	def after_creation

		if !skip_block
      LangSite.all.each do |lang|
          @block = Block.new(:block_name => "Contenu", :lang_site => lang)
          @block.blockable = self
          @block.save
      
      end
    end
  
	end
  
  def alloweds_types
  self.block.allow_types :TitleContent, :TextContent, :ImageContent, :LinkContent, :GalleryContent, :HtmlContent
  
  end
  
	
	scope :recents, -> {order("articles.published_at DESC, articles.created_at DESC")}
	
	scope :between, lambda { |start, stop|
	        after(start).before(stop)
	    }
	
	scope :after, lambda { |date|
	        where("(articles.published_at >= ?)", date )
	    }
	scope :before, lambda { |date|
	        where("(articles.published_at <= ?)", date )
	    }

	
	
	after_initialize do
	    if self.published_at			
			self.published_at = self.published_at.strftime('%d/%m/%Y')
		end
	
	end
  
  after_update do
    logger.debug ["Updating document... ",  __elasticsearch__.delete_document, __elasticsearch__.index_document].join
     # after_destroy { logger.debug ["Deleting document... ", delete_document].join }
  end
  

	

  def as_indexed_json(options={})
        self.as_json(
          include: { lang_articles: { methods: [:html], only: [:title, :description, :html]}#,
                    # authors:    { methods: [:full_name], only: [:full_name] },
                    # comments:   { only: :text }
                   })
      end
	
    
end

#Article.import