package grype

import (
	"github.com/anchore/grype/grype/db"
	"github.com/anchore/grype/grype/store"
	"github.com/anchore/grype/internal/log"
)

func LoadVulnerabilityDB(cfg db.Config, update bool) (*store.Store, *db.Status, *db.Closer, error) {
	dbCurator, err := db.NewCurator(cfg)
	if err != nil {
		return nil, nil, nil, err
	}

	if update {
		log.Debug("looking for updates on vulnerability database")
		_, err := dbCurator.Update()
		if err != nil {
			return nil, nil, nil, err
		}
	}

	storeReader, dbCloser, err := dbCurator.GetStore()
	if err != nil {
		return nil, nil, nil, err
	}

	status := dbCurator.Status()

	p, err := db.NewVulnerabilityProvider(storeReader)
	if err != nil {
		return nil, &status, nil, err
	}

	s := &store.Store{
		Provider:          p,
		MetadataProvider:  db.NewVulnerabilityMetadataProvider(storeReader),
		ExclusionProvider: db.NewMatchExclusionProvider(storeReader),
	}

	closer := &db.Closer{DBCloser: dbCloser}

	return s, &status, closer, nil
}
