module KennaKdi
  class VulnGenerator
    attr_accessor :path_to_cve_json, :cve_ids

    def initialize(path_to_cve_json)
      @path_to_cve_json = path_to_cve_json
      @cve_ids = JSON.parse(File.read(path_to_cve_json)) 
    end

    def vulns(vulns_and_vuln_defs)
      vulns_and_vuln_defs.flat_map do |vdata|
        vdata[:vuln]
      end
    end

    def vuln_defs(vulns_and_vuln_defs)
      vulns_and_vuln_defs.flat_map do |vdata|
        vdata[:vuln_def]
      end
    end

    def multiple_vulns(num_of_vulns)
      num_of_vulns.times.map { random_vuln_and_vuln_def } 
    end

    def sample_cve_ids(num_of_cve)
      num_of_cve.times.map { cve_ids.sample }
    end

    private

    def random_cve_report
      CveReport.new(cve_files.sample)
    end

    def all_cve_reports
      cve_files.map { |file| CveReport.new(file) }
    end

    def cve_report(file_path)
      CveReport.new(file_path)
    end

    def vuln_hash
      scanner_id = Faker::Code.nric
      t = Time.new
      timestamp = t.strftime("%Y-%m-%d %H:%M:%S")

      {
        "scanner_identifier": scanner_id,
        "scanner_type": "KDI Faker Data",
        "created_at": timestamp,
        "last_seen_at": timestamp,
        "status": "open"
      }
    end

    def vuln_def_hash(vuln_hash)
      id = cve_ids.sample
      {
        "scanner_identifier": vuln_hash[:scanner_identifier],
        "scanner_type": vuln_hash[:scanner_type],
        "cve_identifiers": id,
        "name": id
      }
    end

    def random_vuln_and_vuln_def
      # spit out a pair of vuln/vuln_def hashes
      vuln = vuln_hash
      {
        "vuln": vuln,
        "vuln_def": vuln_def_hash(vuln)
      }
    end
  end
end