require 'csv'
require 'date'

namespace :report do

  desc 'Generate CSV file with ALM stats for public sources'
  task :alm_stats => :environment do
    report = AlmStatsReport.new(Source.active.public_sources)
    ReportWriter.write report, contents: report.to_csv, filename: ReportWriter::ALM_STATS_CSV_FILENAME
  end

  desc 'Generate CSV file with ALM stats for private and public sources'
  task :alm_private_stats => :environment do
    report = AlmStatsReport.new(Source.active)
    ReportWriter.write report, contents: report.to_csv, filename: ReportWriter::ALM_STATS_PRIVATE_CSV_FILENAME
  end

  desc 'Zip reports'
  task :zip => :environment do
    LagottoZipUtility.zip_alm_combined_stats!
    LagottoZipUtility.zip_administrative_reports!
    puts "Reports have been compressed!"
  end

  desc 'Export ALM stats report to Zenodo'
  task :export_to_zenodo => [:environment, 'zenodo:requirements_check'] do
    alm_combined_stats_zip_record = FileWriteLog.most_recent_with_name(LagottoZipUtility.alm_stats_zip_filename)

    unless alm_stats_zip_record
      puts  "No zip file (#{File.basename LagottoZipUtility.alm_stats_zip_filename}) found that needs to be exported!"
      next
    end

    publication_date = alm_stats_zip_record.created_at.to_date
    sitenamelong = ENV['SITENAMELONG']
    title = "Cumulative #{sitenamelong} Report - #{publication_date.to_s(:month_and_year)}"
    description = <<-EOS.gsub(/^\s*/, '').gsub(/\s*\n\s*/, " ")
      Article-Level Metrics (ALM) measure the reach and online engagement of scholarly works.
      This #{sitenamelong} report contains the cumulative stats collected for all works through
      #{publication_date.to_s(:long)}. Data are generated by the Lagotto open source software.
      Go to the Lagotto forum for questions or comments.
    EOS

    data_export = ZenodoDataExport.create!(
      name: "alm_stats_report",
      files: [alm_stats_zip_record.filepath],
      publication_date: publication_date,
      title: title,
      description: description,
      creators: [ ENV['CREATOR'] ],
      keywords: ZENODO_KEYWORDS,
      code_repository_url: ENV["GITHUB_URL"]
    )

    DataExportJob.perform_later(id: data_export.id)
  end

  desc 'Generate all article stats reports'
  task :all_stats => [:environment, :alm_stats, :alm_private_stats, :zip, :export_to_zenodo]
end
