class Admin::TaxonsController < ApplicationController
  layout "admin"
  
  before_filter :auth_admin
  
  def import
    require 'csv'
    @path = File.join(Rails.root, "taxons","odonata.csv")

    #Taxon.delete_all
    CSV.foreach(@path,  headers: true, :col_sep => ";" ) do |row|
      t = Taxon.new
      attributes = {}
      row.each do |r|
        if r[0].downcase.to_sym != :aphia_id
          attributes[r[0].downcase.to_sym] = r[1].to_s
        end
      end
      
      Taxon.create(attributes) if !Taxon.find_by_cd_nom(attributes[:cd_nom].to_i)

          
          
      end
      
      
  end
  
  def index
    #@taxons = Taxon.where(["ordre != ?", "<Autres>"]).group(:ordre).all()
    
    
    if !params[:q]
    params[:q] = {}
    end
    
    params[:q][:enabled_true] = "1" if !request.xhr?
    if !params[:q][:s] 
      params[:q][:s] = "lb_nom asc" 
    end
    
    params[:q].delete(:nom_vern_or_nom_valide_or_lb_nom_cont) if params[:q][:nom_vern_or_nom_valide_or_lb_nom_cont] == ""
    params[:q].delete(:enabled_true) if params[:q][:enabled_true] == "0"
    params[:q].delete(:fav_true) if params[:q][:fav_true] == "0"
    
    if params[:all]
      @taxons = Taxon
    else
      @taxons = Taxon.where("taxons.cd_ref = taxons.cd_nom")
    end

    @q = @taxons.ransack(params[:q])
    @taxons = @q.result(distinct: true)


    #if params[:enabled] == "true"
    #  @taxons = @taxons.where(:enabled => true)
    #end
    #if params[:classe]
    #  @taxons = @taxons.where(:classe => params[:classe])
    #end
    
    
    
    #@taxons = Taxon.where("taxons.ordre = ?", "Odonata").all()
    
    
  end

  def sort
    
  end

  def show
    @admin = Admin.find(params[:id])

  end


  def new
    @admin = Admin.new
  
  end

  def edit
    @admin = Admin.find(params[:id])
  
  end

  def create
    @admin = Admin.new(admin_params)
    
    if @admin.save
      @admins = Admin.all
          
    else
      render :action => "new" 
    end
  end

  def update
    @taxon = Taxon.find(params[:id])
    
    if @taxon.update_attributes(taxon_params)

          
    else
      render :action => "edit" 
    end
    
  end
      


  def destroy
    @admin = Admin.find(params[:id])
    
    @admin.destroy if @admin != @current_admin
  
  end
  
  private
      def taxon_params
        params.require(:taxon).permit!
      end



end
