package steps

// |@@| F

import (
	"context"
	"gardening/src/dat/maes"
	"gardening/src/lib/maestro"
	"gardening/src/lib/uploader"
	"gardening/src/mdl"
	"gardening/src/srv/handlers"
	"gardening/src/srv/molders"
)

type SaveEntityStep struct {
	CreateGardenFormMolder *molders.CreateGardenFormMolder
	FilesUploader          *uploader.FilesUploader
	GardenHandler          *handlers.GardenHandler
	Maestro                *maestro.Maestro
}

func (this *SaveEntityStep) Act(ctx context.Context, in *maes.CreateGardenMaeIn, out *maes.CreateGardenMaeOut) (bool, error) {
	var err error
	entity := &mdl.Garden{}
	entity, _ = this.CreateGardenFormMolder.ToEntity(&in.Request.Form, entity)
	this.manageUpload(ctx, in, out, entity)
	out.Response.Garden, err = this.GardenHandler.Create(ctx, entity, nil)
	if err != nil {
		return false, err
	}
	this.Maestro.AddSuccessMessage(&out.Extra, "New garden created")
	return true, nil
}
func (this *SaveEntityStep) manageUpload(ctx context.Context, in *maes.CreateGardenMaeIn, out *maes.CreateGardenMaeOut, entity *mdl.Garden) {
	if in.Request.Files.Picture != "" {
		entity.Picture = this.FilesUploader.Upload(ctx, in.Request.Files.Picture)
	}
}
