package cmds

import (
	"agent/client/events"
	"agent/commons/adata"
	"agent/commons/debug"
	"agent/defines/dcmds"
	"agent/defines/derrs"
	"agent/defines/devent/daction"
	"agent/defines/devent/dcategory"
	"agent/defines/devent/dtype"
	"context"
)

type FolderListCmd struct {
	dcmds.UserToAgentCmd
}

func (c *FolderListCmd) Category() []Category {
	return []Category{dcategory.Agent, dcategory.Rfs, dcategory.Folder}
}

func (c *FolderListCmd) Action() Action {
	return daction.List
}

func (c *FolderListCmd) Execute(ctx context.Context, eventIn IEvent) (eventOut IEvent, err error) {
	debug.Log("FolderListCmd")

	meta := eventIn.Meta()

	path, ok := meta["path"].(string)
	if !ok {
		return nil, derrs.NewIncorrectParamsError("path not found")
	}
	path = normalizePath(path)

	if err = checkFolderAccess(path); err != nil {
		return nil, err
	}

	deep, _ := meta["deep"].(float64)
	full, _ := meta["full"].(bool)
	expandPath, _ := meta["expand_path"].(bool)

	debug.Logf("List: %s, Deep: %d, Full: %v\n\n", path, int(deep), full)

	defer func() {
		if err != nil {
			debug.Logf("FolderList.Error(%s, %v, %v): %s\n", path, deep, expandPath, err)
			return
		}
	}()

	data, err := listFoldersToData(int(deep), full, expandPath, path)
	if err != nil {
		return nil, err
	}

	return events.NewResultEvent(eventIn, dtype.Result, events.NewResultEventOpts{
		Data: adata.NewDataFromMem(data),
	}), nil
}
