package cat

import (
	"bufio"
	"io"
	"os"
	"path"
	"strings"
	"unicode/utf8"
)

func (c Cater) dir(dir string) (e entry, err error) {
	files, err := os.ReadDir(dir)
	if err != nil {
		return
	}

	e.fqname = dir
	e.name = name(dir)
	e.children = []entry{}

	for _, file := range files {
		i, err := file.Info()
		if err != nil {
			return e, err
		}
		path := path.Join(dir, i.Name())

		var ent entry
		if !file.IsDir() {
			ent, err = c.file(path)
		} else {
			ent, err = c.dir(path)
		}
		if err != nil {
			return e, err
		}
		e.children = append(e.children, ent)
	}
	return
}

func (c Cater) file(filePath string) (e entry, err error) {
	file, err := os.Open(filePath)
	if err != nil {
		return
	}
	defer file.Close()

	e.fqname = filePath
	e.name = name(filePath)
	e.children = []entry{}

	// read file into strings.Builder
	var sb strings.Builder
	reader := bufio.NewReader(file)

	for {
		line, err := reader.ReadString('\n')
		if err != nil && err != io.EOF {
			return e, err
		}
		if !utf8.Valid([]byte(line)) {
			e.content = "blob\n"
			return e, nil
		}
		sb.WriteString(line)
		if err == io.EOF {
			break
		}
	}

	e.content = sb.String()

	return
}

func name(name string) string {
	ps := strings.Split(name, "/")
	return ps[len(ps)-1]
}
