package misc

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

func isDirExists(dirPath string) bool {
	if _, err := os.ReadDir(dirPath); err != nil {
		return false
	}
	return true
}

func isDirNotEmpty(dirPath string) bool {
	if entries, err := os.ReadDir(dirPath); err != nil {
		return false
	} else {
		return len(entries) > 0
	}
}

func isFile(filePath string) bool {
	if stat, err := os.Stat(filePath); err != nil {
		return false
	} else {
		return !stat.IsDir()
	}
}

// TestDir tests if directory is exists and not empty
func TestDir(dirPath string) error {
	switch {
	case !isDirExists(dirPath):
		return fmt.Errorf("directory %q is not exists and cannot be used", dirPath)
	case !isDirNotEmpty(dirPath):
		return fmt.Errorf("directory %q is empty and cannot be used", dirPath)
	default:
		return nil
	}
}

// TestFile test if file is exists
func TestFile(filePath string) error {
	if err := TestDir(filepath.Dir(filePath)); err != nil {
		return err
	}
	if !isFile(filePath) {
		return fmt.Errorf("%q not a file or not exists", filePath)
	}
	return nil
}
