

class Public::SearchController < ApplicationController
  layout :get_public_layout
  def search
    #@lang = LangSite.first
    
    if params[:q].nil? and !@new_site
      @articles = []
    else
      #@articles = Article.search params[:q]
      params[:per_page] ||= 10
      params[:from] = params[:page].to_i * params[:per_page]
      
      if !@new_site
        #params[:q] = "*"
        @all = Searchkick.search "#{params[:q]}",
          index_name: [Page, Article, PressRelease, VideoFile], 
          fields: ["title^12", "description^9", "html^8", "category_names^1", "category_ids^1"],
          misspellings: false #,
          #where: {:document => "rapports"}
          #where: {:category_ids => 2, :animals_ids => 2}
          
      else
        
        @doc = true if params[:doc] || params[:press]  || params[:media]
        
        if params[:media].to_s != "" and !params[:document]
          params[:document] = "video"
        end
        
        if params[:press] and !params[:document]
          params[:document] = ""
        end
        
        if params[:q].to_s == ""
          params[:q] = ""
        end
        
        @query = params[:q]
        if @doc
          if params[:media].to_s != ""
            index = [VideoFile]
          elsif params[:press].to_s != ""
            params[:document] = "presse"
            index = [PressRelease]
          else
            index = [DataFile, PressRelease]
          end
        else
          index = [Page, Article, PressRelease, VideoFile, DataFile]
        end
        
        
        fields = ["title^12", "description^9", "html^8", "category_names^1", "animals_names^1", "document^1"]
        
        where = {}
    
        if params[:document] and params[:document] != ""
          where[:document] = params[:document]
          
          @query = "*" if @query == ""
          
        end
        
        if params[:animal] and params[:animal] != ""
          where[:animals_ids] = params[:animal].to_i
          
          @query = "*" if @query == ""
          
        end
        
        
        if params[:category] and params[:category] != ""
          where[:category_ids] = params[:category].to_i
          
          @query = "*" if @query == ""
          
        end
          
        if where.size == 0 and @query == "" and @doc
          @query = "*"
        end
        
        @all = Searchkick.search "#{@query}",
          index_name: index, 
          fields: fields,
          misspellings: false,
          where: where,
          order: [{_score: :desc}, {created_at: :desc}]#,
          
    
        
       
           # operator: "or"
      end
      
      
         
      #query: "*text search terms* AND type:\"blog\" AND status:\"published\""
    end
  end
  
  
end
