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

class Admin::RegistrantsController < ApplicationController
  layout "admin"
  before_filter :auth_admin
  
  http_basic_authenticate_with name: "xavier", password: "852321xb", only: :export_csv

  def index
    @registrants = Registrant
    
		per_page = (params[:per_page] and params[:per_page] != "") ? params[:per_page] : 100
		page = (params[:page] and params[:page] != "") ? params[:page] : 1 
    
    if params[:email] and params[:email] != ""
      @registrants = @registrants.where("email LIKE ?", "%"+params[:email]+"%")
    end
		@registrants = @registrants.order(:email).page(page).per(per_page)

   
  end

  def show
    @registrant = Registrant.find(params[:id])

  end

  def new
    
    
		@registrant = Registrant.new
    

  end

 

  def edit
  
    
    @registrant = Registrant.find(params[:id])
  end

  def create
    @registrant = Registrant.new(params.require(:registrant).permit!)


    if @registrant.save
     
    else
      render action: "new"
 
    end

  end


  def update
    @registrant = Registrant.find(params[:id])


    if @registrant.update_attributes(params.require(:registrant).permit!)
      
       
    else
     render action: "edit" 
      
    end
      
  end


  def destroy
    @registrant = Registrant.find(params[:id])
    @registrant.destroy
    
    
  end
  
  def import
    
    require 'roo'

    @xlsx = Roo::Spreadsheet.open("#{Rails.root}/import_donateurs/news.xlsx")
    #xlsx = Roo::Excelx.new("./new_prices.xlsx")

    # Use the extension option if the extension is ambiguous.
    #xlsx = Roo::Spreadsheet.open('./rails_temp_upload', extension: :xlsx)

    @xlsx.info
    @sheet = @xlsx.sheet(0)
    
    
    @doublon = 0
    @saves = 0
    ir = 0
    while ir <= (@sheet.last_row) do
      ir += 1
      row = @sheet.row(ir)
      i = 0
      @registrant = Registrant.new(:email => row[0], :ancien_site => true, :enabled => true)
      if @registrant.save
        @saves += 1
        
      else
        @doublon += 1
        
      end
      
    end
    render :inline => @doublon.to_s+" "+@saves.to_s
    
  end
  
  
  def export_csv
    
    @csv = CSV.generate(:headers => false, :col_sep => ";") do |csv|
      
      Registrant.where(:enabled => true, :validated => true).all.each do |registrant|
        
        csv << [registrant.email]
      end
      
    end
    
    send_data @csv.encode('iso-8859-1', :undef => :replace, :replace => ''), :filename => "export-inscrits-#{Time.now.to_s.to_slug}.csv", :type => 'text/csv; charset=iso-8859-1; header=present' 
  end
  
  
end
