class Public::MEventsController < ApplicationController
  
  layout :get_public_layout
  
  
  def index
    @m_events = MEvent.all

    params[:search] = params[:search] || []

    @m_events = @m_events.where("start_at >= ? or end_at >= ?", Date.today.beginning_of_day, Date.today.beginning_of_day)

    if params[:search][:m_event_type_title].to_s != ""
      @m_events = @m_events.where(:m_event_type_title => params[:search][:m_event_type_title])
    end

    if params[:search][:circuit_id].to_s != ""
      @m_events = @m_events.where(:circuit_id => params[:search][:circuit_id])
    end

    if params[:search][:organisateur_id].to_s != ""
      @m_events = @m_events.where(:organisateur_id => params[:search][:organisateur_id])
    end

    if params[:search][:circuit_region_id].to_s != ""
      @m_events = @m_events.where(:circuit_id => Circuit.where(:circuit_region_id => params[:search][:circuit_region_id]).ids)
    end



    date_regex = /^(0[1-9]|[12][0-9]|3[01])[\/](0[1-9]|1[012])[\/](19|20)\d\d$/i 
    

    if params[:start] and params[:start] =~ date_regex
      #fsfds = sdfsfd
      @start = Date.parse(params[:start]).beginning_of_day 
      params[:start]= @start.strftime('%d/%m/%Y')
    else
      @start = nil
    end
    
    if true
    
    
      if params[:stop].to_s != "" # and params[:stop] =~ date_regex
        @stop = Date.parse(params[:stop]).end_of_day 
        
        params[:stop]= @stop.strftime('%d/%m/%Y')
        
        
      else
         @stop = nil
      end
    
    end
    
    
    @m_events = @m_events.where("start_at >= ? or end_at >= ?", @start, @start) if @start

    @m_events = @m_events.where("start_at <= ? or end_at <= ?", @stop.end_of_day, @stop.end_of_day) if @stop


    @m_events = sort_by_sorting(@m_events, "start_at ASC")
    respond_to do |format|
      format.html{
      
        params[:search][:per_page] = params[:search][:per_page] || 4
        per_page = params[:search][:per_page]
        page = (params[:page] and params[:page] != "") ? params[:page] : 1 
        @m_events = @m_events.page(page).per(per_page)
      
      }
    end

  end


  def show
    @m_event = MEvent.find(params[:id])

  end


end