package cat

import (
	"fmt"
	"os"
	"strings"
)

type Cater []entry

func Path(paths ...string) (c Cater, err error) {
	c = make(Cater, 0, 10)
	var p os.FileInfo

	for _, path := range paths {
		p, err = os.Stat(path)
		if err != nil {
			return
		}
		var e entry
		if p.IsDir() {
			e, err = c.dir(path)
		} else {
			e, err = c.file(path)
		}
		if err != nil {
			return
		}
		c = append(c, e)
	}

	return
}

func (c Cater) Ignored(ignore ignorer) Cater {
	cat := make(Cater, 0, len(c))
	ok := func(e entry) bool {
		return !ignore.Ignore(e.fqname)
	}

	for _, entry := range c {
		cat = append(cat, entry.filter(ok))
	}

	return cat
}

func (c Cater) ToString(delemiter string) string {
	var sb strings.Builder

	var entries []entry
	entries = c

	for len(entries) > 0 {
		n := make([]entry, 0, len(entries))
		for _, e := range entries {
			if len(e.children) > 0 {
				n = append(n, e.children...)
				continue
			}
			sb.WriteString(fmt.Sprintf(delemiter, e.fqname))
			sb.WriteString(e.content)
		}
		entries = n
	}

	return sb.String()
}

type ignorer interface {
	// Ignore() returns true when the given path shall be Ignored.
	Ignore(path string) bool
}
