package pkg

import (
	"io"
	"path/filepath"
	"strings"

	"gitlab.com/M0M097/pkg/lib/sboRepo"
	"gitlab.com/M0M097/pkg/lib/utils"
)

type packageErrors []string

func (eh *packageErrors) add(pkg *sboRepo.Package, reason string) {
	*eh = append(*eh, pkg.Name()+": "+reason)
}

func (eh *packageErrors) skipPkgAndDependees(pkg *sboRepo.Package, reason string) {
	eh.add(pkg, reason)
	eh.skipDependees(pkg)
}

func (eh *packageErrors) checkDownloads(head *sboRepo.Package, tmpDir string) {
	head.Iterate(func(pkg *sboRepo.Package) {
		md5sums := pkg.Md5sums()
		for i, DownloadName := range pkg.DownloadNames() {
			var msg string
			fullPath := filepath.Join(tmpDir, DownloadName)
			switch {
			case !utils.Exists(fullPath):
				msg = "file not found"
			case !utils.IsMD5SumMatch(md5sums[i], fullPath):
				msg = "MD5Sum Mismatch. Run with -" + MD5_FLAG + " to disable MD5Sum Check"
			default:
				continue
			}
			eh.add(pkg, fullPath+": "+msg)
			eh.skipDependees(pkg)
		}
	})
}

func (eh *packageErrors) skipDependees(pkgToDelete *sboRepo.Package) {
	for _, dependee := range pkgToDelete.Dependees() {
		if dependee.IsInList() {
			eh.add(dependee, "Depends on "+pkgToDelete.Name())
			eh.skipDependees(dependee)
		}
	}
	pkgToDelete.Del()
}

func (eh *packageErrors) final(w io.Writer) {
	s := "All packages installed successfully"
	if len(*eh) != 0 {
		s = utils.Banner("Skipped Packages", strings.Join(*eh, "\n"))
	}
	w.Write([]byte(s + "\n"))
}
