# frozen_string_literal: true

class Vulnerability::VersionChart
  include ChartHelper

  SEVERITY_LEGENDS = { critical: [I18n.t('projects.vulnerabilities.severity.critical')],
                       high: [I18n.t('projects.vulnerabilities.severity.high')],
                       medium: [I18n.t('projects.vulnerabilities.severity.medium')],
                       low: [I18n.t('projects.vulnerabilities.severity.low')],
                       unknown_severity: [I18n.t('projects.vulnerabilities.unknown_severity')] }.freeze

  def initialize(release_history, bdsa_visible = false)
    @release_history = release_history
    @bdsa_visible = bdsa_visible
    @default_options = VULNERABILITY_VERSION_CHART_DEFAULTS.deep_dup
  end

  def data
    set_xaxis
    series.deep_merge(chart_watermark)
  end

  private

  def set_xaxis
    @default_options[:xAxis][:categories] = @release_history.map(&:version)
  end

  def series
    color_map = ['#0c1c33', '#183867', '#4b6b9a', '#a5b5cd', '#cce1e9']
    SEVERITY_LEGENDS.keys.each_with_index do |level, index|
      legend = SEVERITY_LEGENDS[level]
      @default_options[:series][index] = { name: "CVE #{legend[0]}",
                                           color: color_map[index],
                                           data: vulnerabilities_count_by_severity(level.to_s),
                                           stack: 'CVE' }
    end

    bdsa_series if @bdsa_visible
    @default_options
  end

  def bdsa_series
    bdsa_color_map = ['rgb(90,16,12)', 'rgb(156,37,31)', 'rgb(231,140,135)', 'rgb(154,155,156)', '#D3D3D3']
    SEVERITY_LEGENDS.keys.each_with_index do |level, index|
      legend = SEVERITY_LEGENDS[level]
      @default_options[:series][index + 5] = { name: "BDSA #{legend[0]}",
                                               color: bdsa_color_map[index],
                                               data: vulnerabilities_count_by_severity("bdsa_#{level}"),
                                               stack: 'BDSA' }
    end
  end

  def vulnerabilities_count_by_severity(level)
    @release_history.map { |r| r.attributes[level] }
  end
end
