package extractor

import (
	"fmt"
	"regexp"
)

var (
	// ex:
	// CVE-2018-1111
	// CVE: 2018-1111
	// CVE: CVE-2018–14064
	// CVE: cve-2018-8002
	// CVE: CVE 2018-7719
	// CVE : CVE- 2018-7198
	// CVE : [CVE-2018- 11034]
	// CVE: 2017-13056
	// CVE; 2016-0953
	// CVE : 2012-3755
	// CVE 2012-0550
	cveIDRegexp1 = regexp.MustCompile(`(?i)CVE\s?[-–:;]?\s?([0-9]+)[-–]\s?([0-9]+)`)
	// ex: CVE Number:   2011-4189
	cveIDRegexp2 = regexp.MustCompile(`CVE Number\s*[:;]\s*([0-9]+)[-–]([0-9]+)`)
	// ex:
	// [ 'CVE', '2009-0184' ]
	// ['CVE',    '2005-2265']
	// [ 'CVE', '2003-0352'  ]
	// [ 'CVE', '2011-2404 ']
	cveIDRegexp3 = regexp.MustCompile(`\[\s*'CVE'\s*,\s*'([0-9]+)[-–]([0-9]+)\s*'\s*\]`)
	// ex: ['CVE'     => '2008-6825']
	cveIDRegexp4 = regexp.MustCompile(`\[\s*'CVE'\s*=>\s*'([0-9]+)[-–]([0-9]+)\s*'\s*\]`)
	// ex : CVE : [2014-3443]
	cveIDRegexp5 = regexp.MustCompile(`CVE\s*:\s*\[([0-9]+)[-–]([0-9]+)\]`)
)

// ExtractCveID :
func ExtractCveID(file []byte) (cveIDs []string) {
	uniqCveID := map[string]struct{}{}
	regxps := []*regexp.Regexp{
		cveIDRegexp1,
		cveIDRegexp2,
		cveIDRegexp3,
		cveIDRegexp4,
		cveIDRegexp5,
	}

	for _, re := range regxps {
		results := re.FindAllSubmatch(file, -1)
		for _, matches := range results {
			if 2 < len(matches) {
				cveID := fmt.Sprintf("CVE-%s-%s", matches[1], matches[2])
				uniqCveID[cveID] = struct{}{}
			}
		}
	}

	for cveID := range uniqCveID {
		cveIDs = append(cveIDs, cveID)
	}
	return cveIDs
}
