# -*- encoding : utf-8 -*-

class Admin::EventsController < ApplicationController
	before_filter :authenticate_admin!

	layout "admin"

	before_filter :find_events


	def index 

	end


	def cible
		@events = Event.all

		render :layout => false
	end

	
	def new
		if params[:event_id] and Event.find(params[:event_id])
			@event = Event.find(params[:event_id]).dup
			@event.event_id = params[:event_id]
		else
			@event = Event.new
		
		end

	end

	def edit
		@event = Event.find(params[:id])
		
		render :layout => false
	end


	def create
		@event = Event.new(params[:event])


		if @event.save
		
		
			flash[:notice] = "L'événement à été ajouté avec succès."
		
			self.find_events #reload events to show new events in the list sort by date.

		else
			render :action => "new" 
		
		end
	
	end
	

	def update
		@event = Event.find(params[:id])

		if @event.update_attributes(params[:event])
			flash[:notice] = "L'événement à été modifié avec succès."
		else
			render :action => "edit" 
			
		end

	end


	def destroy
		@event = Event.find(params[:id])
		@event.destroy

	end
	
	
	protected
	
	def find_events
		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
			start = Date.parse(params[:start]).beginning_of_day 
			params[:start]= start.strftime('%d/%m/%Y')
		else
			params[:start] = "Début"
		end
		if params[:stop] and params[:stop] =~ date_regex
			stop = Date.parse(params[:stop]).end_of_day 
			params[:stop]= stop.strftime('%d/%m/%Y')
		 else
		 	params[:stop] = "Fin"
		end
		
		@events = Event.order('start_at, stop_at')
		@events = @events.after(start) if start
		@events = @events.before(stop) if stop
		per_page = (params[:per_page] and params[:per_page] != "") ? params[:per_page] : 15
		page = (params[:page] and params[:page] != "") ? params[:page] : 1 
		@events = @events.page(page).per(per_page)

		#@events = Event.order('start_at, stop_at').after(start).before(stop)
	end
end
