package cmds

import (
	"agent/commons/debug"
	"agent/commons/utils"
	"agent/defines/dcmds"
	"agent/defines/derrs"
	"agent/defines/devent/daction"
	"agent/defines/devent/dcategory"
	"context"
	"os"
	"path/filepath"
)

type ItemDeleteCmd struct {
	dcmds.UserToAgentCmd
}

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

func (c *ItemDeleteCmd) Action() Action {
	return daction.Delete
}

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

	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("ItemDelete.Error(%s): %s\n", path, err)
			return
		}
	}()

	dir := filepath.Dir(path)

	if utils.FileIsExist(path) {
		debug.Logf("DeleteFile: %s\n\n", path)
		err = os.Remove(path)
	} else if utils.DirIsExist(path) {
		debug.Logf("DeleteFolder: %s\n\n", path)
		err = os.RemoveAll(path)
	} else {
		return nil, derrs.NewIncorrectParamsError("item does not exist")
	}

	if err != nil {
		return nil, err
	}
	if len(dir) == 0 {
		return nil, nil
	}

	return listFoldersToResultEvent(eventIn, dir)
}
