package inout

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

type Folder struct {
	Nume       string
	Fisiere    []File
	Subfoldere []Folder
}

type File struct {
	Nume string
	Path string
}

func SafeDir(path string) error {
	path = filepath.Clean(path)
	if strings.HasPrefix(path, "..") || filepath.IsAbs(path) {
		return fmt.Errorf("Invalid Path")
	}
	return nil
}

func GetFolderStructure(path string, f *Folder) error {
	entries, err := os.ReadDir(path)
	if err != nil {
		return err
	}
	if filepath.Clean(path) != "notes_folder" {
		f.Nume = filepath.Base(path)
	} else {
		f.Nume = "notes_folder"
	}
	for _, entry := range entries {

		if entry.IsDir() {
			sub := Folder{}
			err = GetFolderStructure(filepath.Join(path, entry.Name()), &sub)
			if err != nil {
				return err
			}
			f.Subfoldere = append(f.Subfoldere, sub)
		} else {
			fisier := File{
				Nume: entry.Name(),
				Path: filepath.Join(path, entry.Name()),
			}
			f.Fisiere = append(f.Fisiere, fisier)
		}
	}
	return nil
}
