# frozen_string_literal: true

require 'json'
require 'rest-client'

module Abaci
  # Helper class to access data from influx
  class Sentinel
    extend Base

    class << self
      # Caches and returns a copy of the parsed json response from sentinels API.
      def data
        return @data if instance_variable_defined?(:@data)
        duration = Abaci.parse_duration(config(:last))
        response = RestClient.get material('sentinel_url'), accept: :json, params: { from: Time.now.to_i * 1000 - duration }, authorization: "Bearer #{material('sentinel_bouncer_token')}"

        raise 'Unable to request sentinel error aggregates' unless response.code == 200

        @data = JSON.parse(response.body)['aggregates'].collect { |timestamp, time_slice| [timestamp.to_i, time_slice] }.to_h
      end

      # Returns the error count per minute.
      def errors
        @errors ||= data.collect { |timestamp, time_slice| [timestamp, time_slice['errorsByBuild'].values.collect { |counts| counts['pageCount'] }.reduce(0, &:+)] }.to_h
      end

      # Returns minutely error counts per minute per build.
      def errors_by_build
        @errors_by_build ||= data.collect { |timestamp, time_slice| [timestamp, time_slice['errorsByBuild'].collect { |build_id, counts| [build_id, counts['pageCount']] }.to_h] }.to_h
      end
      
    end
  end
end
