package cmds

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

type FileGetCmd struct {
	dcmds.UserToAgentCmd
}

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

func (c *FileGetCmd) Action() Action {
	return daction.Get
}

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

	meta := eventIn.Meta()

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

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

	if !utils.FileIsExist(path) {
		return nil, derrs.NewIncorrectParamsError(fmt.Sprintf("file does not exist: %s", path))
	}

	return events.NewResultEvent(eventIn, dtype.Result, events.NewResultEventOpts{
		Data:    adata.NewDataFromFile(path),
		Cleanup: false,
	}), nil
}
