package db

import (
	"fmt"
	"strings"

	version "github.com/hashicorp/go-version"
	log "github.com/kotakanbe/go-cve-dictionary/log"
	"github.com/kotakanbe/go-cve-dictionary/models"

	"github.com/knqyf263/go-cpe/common"
	"github.com/knqyf263/go-cpe/matching"
	"github.com/knqyf263/go-cpe/naming"
)

// DB is interface for a database driver
type DB interface {
	Name() string
	CloseDB() error
	Get(string) (*models.CveDetail, error)
	GetMulti([]string) (map[string]models.CveDetail, error)
	GetByCpeURI(string) ([]models.CveDetail, error)
	InsertJvn([]models.CveDetail) error
	InsertNvdXML([]models.CveDetail) error
	InsertNvdJSON([]models.CveDetail) error
	CountNvd() (int, error)
	UpsertFeedHash(models.FeedMeta) error
	GetFetchedFeedMeta(string) (*models.FeedMeta, error)
	GetFetchedFeedMetas() ([]models.FeedMeta, error)
}

// NewDB return DB accessor.
func NewDB(dbType, dbpath string, debugSQL bool) (DB, bool, error) {
	switch dbType {
	case dialectSqlite3, dialectMysql, dialectPostgreSQL:
		return NewRDB(dbType, dbpath, debugSQL)
	case dialectRedis:
		return NewRedis(dbType, dbpath, debugSQL)
	}
	return nil, false, fmt.Errorf("Invalid database dialect, %s", dbType)
}

func chunkSlice(l []models.CveDetail, n int) chan []models.CveDetail {
	ch := make(chan []models.CveDetail)

	go func() {
		for i := 0; i < len(l); i += n {
			fromIdx := i
			toIdx := i + n
			if toIdx > len(l) {
				toIdx = len(l)
			}
			ch <- l[fromIdx:toIdx]
		}
		close(ch)
	}()
	return ch
}

func parseCpeURI(cpe22uri string) (*models.CpeBase, error) {
	wfn, err := naming.UnbindURI(cpe22uri)
	if err != nil {
		return nil, err
	}

	return &models.CpeBase{
		URI:             naming.BindToURI(wfn),
		FormattedString: naming.BindToFS(wfn),
		WellFormedName:  wfn.String(),
		CpeWFN: models.CpeWFN{
			Part:            fmt.Sprintf("%s", wfn.Get(common.AttributePart)),
			Vendor:          fmt.Sprintf("%s", wfn.Get(common.AttributeVendor)),
			Product:         fmt.Sprintf("%s", wfn.Get(common.AttributeProduct)),
			Version:         fmt.Sprintf("%s", wfn.Get(common.AttributeVersion)),
			Update:          fmt.Sprintf("%s", wfn.Get(common.AttributeUpdate)),
			Edition:         fmt.Sprintf("%s", wfn.Get(common.AttributeEdition)),
			Language:        fmt.Sprintf("%s", wfn.Get(common.AttributeLanguage)),
			SoftwareEdition: fmt.Sprintf("%s", wfn.Get(common.AttributeSwEdition)),
			TargetSW:        fmt.Sprintf("%s", wfn.Get(common.AttributeTargetSw)),
			TargetHW:        fmt.Sprintf("%s", wfn.Get(common.AttributeTargetHw)),
			Other:           fmt.Sprintf("%s", wfn.Get(common.AttributeOther)),
		},
	}, nil
}

func makeVersionConstraint(dict models.Cpe) string {
	constraints := []string{}
	if dict.VersionStartIncluding != "" {
		constraints = append(constraints, ">= "+dict.VersionStartIncluding)
	}
	if dict.VersionStartExcluding != "" {
		constraints = append(constraints, "> "+dict.VersionStartExcluding)
	}
	if dict.VersionEndIncluding != "" {
		constraints = append(constraints, "<= "+dict.VersionEndIncluding)
	}
	if dict.VersionEndExcluding != "" {
		constraints = append(constraints, "< "+dict.VersionEndExcluding)
	}
	return strings.Join(constraints, ", ")
}

func match(specified common.WellFormedName, cpe models.Cpe) (bool, error) {
	wfn, err := naming.UnbindURI(cpe.URI)
	if err != nil {
		return false, err
	}

	if wfn.Get("part") != specified.Get("part") ||
		wfn.Get("vendor") != specified.Get("vendor") ||
		wfn.Get("product") != specified.Get("product") {
		return false, nil
	}

	if matching.IsEqual(specified, wfn) {
		log.Debugf("%s equals %s", specified.String(), cpe.URI)
		return true, nil
	}
	ver := fmt.Sprintf("%s", specified.Get(common.AttributeVersion))

	switch ver {
	case "NA", "ANY":
		if matching.IsSuperset(wfn, specified) {
			log.Debugf("%s is superset of %s", cpe.URI, specified.String())
			return true, nil
		}
		if matching.IsSubset(wfn, specified) {
			log.Debugf("%s is subset of %s", cpe.URI, specified.String())
			return true, nil
		}

	default:
		ver = strings.Replace(ver, `\`, "", -1)
		v, err := version.NewVersion(ver)
		if err != nil {
			return false, err
		}
		constraintStr := makeVersionConstraint(cpe)
		if constraintStr != "" {
			constraints, err := version.NewConstraint(constraintStr)
			if err != nil {
				return false, err
			}
			if constraints.Check(v) {
				log.Debugf("%s satisfies constraints %s", v, constraintStr)
				return true, nil
			}
		}
	}
	return false, nil
}

func matchCpe(specified common.WellFormedName, cve *models.CveDetail) (bool, error) {
	cpes := []models.Cpe{}
	if cve.NvdJSON != nil {
		cpes = append(cpes, cve.NvdJSON.Cpes...)
	}
	if cve.NvdXML != nil {
		cpes = append(cpes, cve.NvdXML.Cpes...)
	}
	if cve.Jvn != nil {
		cpes = append(cpes, cve.Jvn.Cpes...)
	}
	for _, cpe := range cpes {
		match, err := match(specified, cpe)
		if err != nil {
			return false, err
		}
		if match {
			return true, nil
		}
	}
	return false, nil
}
