=begin
ActiveAdmin.register_page "Download Score CSV" do
  menu :parent => 'Misc'

  page_action :create_csv, :method => :post do

    start_time = params[:score_exports][:start]
    end_time = params[:score_exports][:end]

    if start_time.blank?
      start_time = '1900-01-01'
    end
    start_time = "#{start_time}"
    if end_time.blank?
      end_time = (Time.now + 1.days).strftime('%F')
    else
      end_time = "#{end_time}"
    end

    scores = ScoreHistory
      .select("from_city, from_regions.regionname as from_region_name, from_countries.countryname as from_country_name, from_isp,
                 to_city,   to_regions.regionname as to_region_name,     to_countries.countryname as to_country_name, to_isp,
                 min(score_histories.score) as min_latency, max(score_histories.score) as max_latency, avg(score_histories.score) as mean_latency, median(CAST(score_histories.score AS NUMERIC)) as median_latency, count(score_histories.score) as score_count")
      .joins('LEFT JOIN countries AS from_countries ON from_countries.countrycode  = from_country')
      .joins('LEFT JOIN countries AS to_countries   ON to_countries.countrycode    = to_country')
      .joins('LEFT JOIN regions   AS from_regions   ON from_regions.region         = from_region')
      .joins('LEFT JOIN regions   AS to_regions     ON to_regions.region           = to_region')
      .where("score_dt BETWEEN DATE '#{start_time}' AND DATE '#{end_time}'")
      .order('from_city, from_regions.regionname, from_countries.countryname, from_isp, to_city, to_regions.regionname, to_countries.countryname, to_isp')
      .group('from_city, from_regions.regionname, from_countries.countryname, from_isp, to_city, to_regions.regionname, to_countries.countryname, to_isp')
      .limit(1_000_000)


    csv_string = CSV.generate do |csv|
      csv << ["From Country", "From Region", "From City", "From ISP", "To Country", "To Region", "To City", "To ISP", "Min Latency", "Max Latency", "Median Latency", "Mean Latency", 'Score Count']

      scores.each do |score|
        puts score.inspect
        csv << [score.from_country_name, score.from_region_name, score.from_city, score.from_isp,
                score.to_country_name, score.to_region_name, score.to_city, score.to_isp,
                score[:min_latency], score[:max_latency], score[:median_latency], score[:mean_latency], score[:score_count]]
      end
    end


    send_data csv_string,
              :type => 'text/csv; charset=iso-8859-1; header=present',
              :disposition => "attachment; filename=score_export-#{start_time}-#{end_time}.csv"
  end


  content :title => "Export Score" do
    columns do
      column do
        semantic_form_for :score_exports, :url => admin_download_csv_create_csv_path, :builder => ActiveAdmin::FormBuilder do |f|
          f.inputs do
            f.input :start, :as => :datepicker
            f.input :end, :as => :datepicker
          end
          f.actions do
            f.action :submit, :label => 'Download CSV'
          end
        end
      end
      column do
        panel "Usage" do
          span "Select a start day and end day to generate a CSV with a score summary. Both fields are optional."
        end
        panel "Limitation 1" do
          div do
            span do "The system limits the number of rows exported to 1,000,000" end
          end
        end
        panel "Limitation 2" do
          div do
            span do "This report uses the score_histories table, which can lag up to 1 hour behind data.  You can force a score_history sweep by going to" end
            span do link_to "Resque", "#{Gon.global.prefix}/resque/schedule" end
            span do " and then clicking 'Queue Now' for ScoreHistorySweeper.  When the job count goes from 1 to 0, the score_histories table is now completely up-to-date, and you can make a 'fresh' CSV." end
          end
        end
      end
    end


    #panel "Upaid Registrations" do
    #  table_for Registration.unpaid.limit(10).order('created_at desc') do
    #    column "Registration" do |registration|
    #      link_to registration.id, admin_registration_path(registration)
    #    end
    #    column :user
    #    column :tour
    #    column "Payment" do |registration|
    #      status_tag((registration.paid? ? "Received" : "Pending"), (registration.paid? ? :ok : :warning))
    #    end
    #  end
    #end

  end
end
=end
