<script type="text/javascript" src="<%= root_path %>javascripts/chart.min.js"></script>
<script type="text/javascript" src="<%= root_path %>javascripts/chartjs-plugin-annotation.min.js"></script>
<script type="text/javascript" src="<%= root_path %>javascripts/base-charts.js"></script>
<script type="text/javascript" src="<%= root_path %>javascripts/metrics.js"></script>

<div class="header-container">
  <h1><%= t('Metrics') %></h1>

  <div>
    <a target="blank" href="https://github.com/mperham/sidekiq/wiki/Metrics"><span class="info-circle" title="Click to learn more about metrics">?</span></a>
  </div>
</div>

<%
  table_limit = 20
  chart_limit = 5
  job_results = @query_result.job_results.sort_by { |(kls, jr)| jr.totals["s"] }.reverse.first(table_limit)
  visible_kls = job_results.first(chart_limit).map(&:first)
%>

<% if job_results.any? %>
  <canvas id="job-metrics-overview-chart"></canvas>

  <script>
    window.jobMetricsChart = new JobMetricsOverviewChart(
      document.getElementById("job-metrics-overview-chart"),
      <%= Sidekiq.dump_json({
        series: job_results.map { |(kls, jr)| [kls, jr.dig("series", "s")] }.to_h,
        marks: @query_result.marks.map { |m| [m.bucket, m.label] },
        labels: @query_result.buckets,
        visibleKls: visible_kls,
        yLabel: t('TotalExecutionTime'),
        units: t('Seconds').downcase,
        markLabel: t('Deploy'),
      }) %>
    )
  </script>
<% end %>

<div class="table_container">
  <table class="table table-bordered table-striped table-hover">
    <tbody>
      <tr>
        <th><%= t('Name') %></th>
        <th><%= t('Success') %></th>
        <th><%= t('Failure') %></th>
        <th><%= t('TotalExecutionTime') %></th>
        <th><%= t('AvgExecutionTime') %></th>
      </tr>
      <% if job_results.any? %>
        <% job_results.each_with_index do |(kls, jr), i| %>
          <tr>
            <td>
              <div class="metrics-swatch-wrapper">
                <% id = "metrics-swatch-#{kls}" %>
                <input
                  type="checkbox"
                  id="<%= id %>"
                  class="metrics-swatch"
                  value="<%= kls %>"
                  <%= visible_kls.include?(kls) ? 'checked' : '' %>
                />
                <code><a href="<%= root_path %>metrics/<%= kls %>"><%= kls %></a></code>
              </div>
              <script>jobMetricsChart.registerSwatch("<%= id %>")</script>
            </td>
            <td><%= jr.dig("totals", "p") - jr.dig("totals", "f") %></td>
            <td><%= jr.dig("totals", "f") %></td>
            <td><%= jr.dig("totals", "s").round(2) %> seconds</td>
            <td><%= jr.total_avg("s").round(2) %> seconds</td>
          </tr>
        <% end %>
      <% else %>
          <tr><td colspan=5><%= t("NoDataFound") %></td></tr>
      <% end %>
    </tbody>
  </table>
</div>

<p><small>Data from <%= @query_result.starts_at %> to <%= @query_result.ends_at %></small></p>
