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

class Admin::FoyersController < ApplicationController
	before_filter :authenticate_admin!

	
	layout "admin"
	navigation :foyers


	def index
		@foyers = Foyer.order('surname ASC')
		if request.xhr?
			render :layout => false
			
		end
	end

	def new

	
		@foyer = Foyer.new()
	end
	
	def create

		@foyers = Foyer.order('surname ASC')
		@foyer = Foyer.new(params[:foyer])

		
		if @foyer.save
			flash[:notice] = "Le foyer à bien été créé."
			
			respond_to do |format|
				format.js
			end
			
		else
			
			respond_to do |format|
				format.js { render :action => :new}
			end
					
		end
	end


	def edit

		
		@foyer = Foyer.find(params[:id])
	

	end

	def update
	
		
		@foyer = Foyer.find(params[:id])
		
		if @foyer.update_attributes(params[:foyer])
			flash[:notice] = "Le foyer à bien été modifié."
			
			respond_to do |format|
				format.html { redirect_to(admin_foyers_path()) }
				format.js
			end
			
		else
			respond_to do |format|
				format.html { render :action => :edit}
				format.js { render :action => :edit}
			end		
		end
	end


	def destroy
		@foyer = Foyer.find(params[:id])
		@foyer.destroy
	
	
		flash[:notice] = "Le foyer à bien été supprimé."
	end
  def import
	if params[:dump] and  params[:dump][:file]
		require 'csv'
		require 'iconv'
	
		Foyer.destroy_all
	
		@parsed_file=CSV.parse(Iconv.conv('utf-8', 'ISO-8859-1', params[:dump][:file].read),:col_sep =>  ';')
		#@parsed_file=CSV::Reader.parse(params[:dump][:file], ';')
		@parsed_file.each do |row|
			if row[19] == "LYCEE PIERRE BEGHIN"
			
	
			
				if Foyer.find_by_fcpe_id(row[0])
					@foyer = Foyer.find_by_fcpe_id(row[0])
				else
					@foyer = Foyer.new(
						:fcpe_id => row[0],
						:surname => row[1],
						:name => row[2],
						:email => row[8],
						:city => row[6].to_s+" "+row[7].to_s
		
					)
					@foyer.save
				end
			
				@foyer.studients << Studient.create(:surname => row[17], :name => row[18], :classe => row[20].to_s+" "+row[21].to_s)
			
			end
		end
		redirect_to :back, :alert => "Le nouveau fichier à bien été importé."
	else
		redirect_to :back, :alert => "Aucun fichier n'a été séléctionner."
	end
  end

  def import_validation
  end

end
