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

class Admin::StatLinesController < ApplicationController
  layout "admin"
  before_action :auth_admin

  before_action :admin_space
  
  def admin_space
    @admin_space = "statistiques"
  end
  
  def index
    @stat_lines = StatLine.all

    @stat_lines = sort_by_sorting(@stat_lines, "id DESC")
    respond_to do |format|
      format.html{
      
        params[:search][:per_page] = params[:search][:per_page] || 100
        per_page = params[:search][:per_page]
        page = (params[:page] and params[:page] != "") ? params[:page] : 1 
        @stat_lines = @stat_lines.page(page).per(per_page)
      
      }
      
      format.csv { 
          @headers = []
          @columns = []
          StatLine.qi_table_order.each do |key, value|
          
            if value.instance_of? Hash
              name = value[:name]
            else
              name = value
            end
          
            if name != "Actions"
              @headers << name.to_s
              @columns << key
            end
          
          end
    
    
    
          xlsx_package = Axlsx::Package.new
            wb = xlsx_package.workbook
            wb.add_worksheet(name: "import") do |sheet|
              sheet.add_row @headers
              
              @stat_lines.each do |stat_line|
                line = []
            
                @columns.each do |column|
              
                  if (stat_line.respond_to?("csv_"+column.to_s))
                    line << stat_line.send("csv_"+column.to_s)
                  elsif (stat_line.respond_to?(column))
                    
                      line << stat_line.send(column.to_s)
                    
                  else
                    line << column.to_s
                  end
              
                end
            
                
                sheet.add_row line, types: line.map{|t| cell_type_from_value(t)}
              end
              
              
            end
            
            @final_file = "#{Rails.root}/private_medias/export-stats-#{Time.now.to_s.to_slug}.xlsx"
      

            xlsx_package.serialize(@final_file)  
  
        
            send_file @final_file
        
  
  
        }
      
    end
  end

  def show
    @stat_line = StatLine.find(params[:id])

  end

  def new
    @stat_line = StatLine.new
  
  end

  def edit
    @stat_line = StatLine.find(params[:id])
    
  end

  def create
    @stat_line = StatLine.new(params.require(:stat_line).permit!)

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

  end


  def update
    @stat_line = StatLine.find(params[:id])


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


  def destroy
    @stat_line = StatLine.find(params[:id])
    @stat_line.destroy
    
  end
end