class ApiSnapshotUtility

  def self.snapshot_later(endpoints_to_snapshot, options={})
    endpoints_to_snapshot = [endpoints_to_snapshot].flatten
    benchmark = options[:benchmark] || ENV["BENCHMARK"] || false

    host = options[:host] || ENV["SERVERNAME"]
    host = "http://#{host}" unless host =~ /^https?:\/\//

    pages_per_job =  options[:pages_per_job] || (ENV["PAGES_PER_JOB"] && ENV["PAGES_PER_JOB"].to_i)
    pages_per_job ||= 10

    snapshot_dir = options[:snapshot_dir] || ENV["SNAPSHOT_DIR"] || ApiSnapshot.default_snapshot_dir

    start_page = options[:start_page] || (ENV["START_PAGE"] && ENV["START_PAGE"].to_i)
    stop_page = options[:stop_page] || (ENV["STOP_PAGE"] && ENV["STOP_PAGE"].to_i)

    filename_ext = options[:filename_ext] || ENV["FILENAME_EXT"] || ApiSnapshot::FILENAME_EXT
    mode = options[:mode] || ApiSnapshot::CREATE_MODE

    endpoints_to_snapshot.each do |endpoint|
      endpoint = "/#{endpoint}" unless endpoint.starts_with?("/")
      url = "#{host}#{endpoint}"

      snapshot = ApiSnapshot.create!(
        benchmark: benchmark,
        filename_ext: filename_ext,
        num_pages: pages_per_job,
        snapshot_dir: snapshot_dir.to_s,
        start_page: start_page,
        stop_page: stop_page,
        url: url,
        mode: mode
      )
      ApiSnapshotJob.perform_later id:snapshot.id, upload_on_finished: options[:upload_on_finished]
    end
  end

  def self.zip(snapshot)
    zipper = LagottoZipUtility.new(
      zip_filepath: snapshot.zip_filepath,
      filemap: {
        snapshot.snapshot_filepath => File.basename(snapshot.snapshot_filepath),
        Rails.root.join("docs/readmes/api_snapshot.md") => "README.md"
      }
    )
    zipper.zip!
    snapshot.zip_filepath
  end

  def self.export_to_zenodo(snapshot)
    publication_date = snapshot.created_at.to_date
    sitenamelong = ENV['SITENAMELONG']

    title = "API Snapshot of #{snapshot.url} on #{snapshot.snapshot_date}"
    description = <<-EOS.gsub(/^\s*/, '').gsub(/\s*\n\s*/, " ")
      Article-Level Metrics (ALM) measure the reach and online engagement of scholarly works.
      This #{sitenamelong} API snapshot contains the entirety of the #{snapshot.url}
      end_point at the time it was generated on #{publication_date}.
      Data are generated by the Lagotto open source software.
      Go to the Lagotto forum for questions or comments.
    EOS

    data_export = ZenodoDataExport.create!(
      name: "api_snapshot",
      files: [snapshot.zip_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

end
