// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
// All rights reserved.

// match.go
package main

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

func matchFilePattern(dirName string, pattern string, join bool) (fileList []string, err error) {
	var entries []os.DirEntry
	if entries, err = os.ReadDir(dirName); err == nil {
		for _, entry := range entries {
			if entry.Type().IsRegular() {
				var match bool
				if match, err =filepath.Match(pattern, entry.Name()); err != nil {
					fileList = nil
					break
				}
				if match {
					if fileList == nil {
						fileList = make([]string, 0, 1)
					}
					if join {
						fileList = append(fileList, path.Join(dirName, entry.Name()))
					} else {
						fileList = append(fileList, entry.Name())
					}
				}
			}
		}
	}
	return
}

func matchPathPattern(pathPattern string) (fileList []string, err error) {
	dirName := path.Dir(pathPattern)
	pattern := path.Base(pathPattern)
	return matchFilePattern(dirName, pattern, true) 
}


func isPattern(name string) bool{
	return strings.ContainsAny(name, "*?[]")
} 