package gio

import (
	"os"
	"path/filepath"
	"slices"
	"strings"
)

// ReadDir 读取文件夹包含其子文件中的所有文件, 并返回绝对路径
// 当指定 suffix 时则仅查找文件后缀为 suffix 的文件
func ReadDir(path string, suffix ...string) ([]string, error) {
	file, err := os.ReadDir(filepath.Join(path))
	if err != nil {
		return nil, err
	}
	fileList := make([]string, 0, 1024)
	for i := 0; i < len(file); i++ {
		if file[i].IsDir() {
			var fs []string
			fs, err = ReadDir(filepath.Join(path, file[i].Name()), suffix...)
			if err != nil {
				return nil, err
			}
			fileList = append(fileList, fs...)
			continue
		}
		if len(suffix) > 0 {
			found := slices.ContainsFunc(suffix, func(s string) bool {
				return strings.HasSuffix(file[i].Name(), s)
			})
			if !found {
				continue
			}
		}
		fileList = append(fileList, filepath.Join(path, file[i].Name()))
	}
	return fileList, nil
}
