require 'debci/db'

module Debci
  JobLatency = Struct.new(:arch, :latency) do
    def in_words
      days = latency.in_days.to_i
      hours = (latency - days.days).in_hours.to_i
      minutes = (latency - days.days - hours.hours).in_minutes.to_i
      parts = {
        day: days,
        hour: hours,
        minute: minutes
      }.reject { |_, v| v == 0 }.map do |k, v|
        unit = v == 1 ? k : "#{k}s"
        "#{v} #{unit}"
      end
      parts.join(', ')
    end

    def self.get
      if !@data || !@timestamp || Time.now > (@timestamp + 1.hour)
        @data = fetch
        @timestamp = Time.now
      end
      @data
    end

    def self.reset!
      @data = @timestamp = nil
    end

    def self.fetch
      query = <<-ENDQUERY
        SELECT arch, avg(received_at - created_at) AS latency
        FROM jobs
        WHERE created_at > $1 AND received_at > $2 AND status != 'tmpfail'
        GROUP BY arch
      ENDQUERY

      now = Time.now
      created_since = now - 1.month
      finished_since = now - 6.hours
      results = ActiveRecord::Base.connection.exec_query(
        query,
        "Job latency per architecture",
        [created_since, finished_since]
      )
      results.cast_values.map do |row|
        self.new(*row)
      end
    end
  end
end
