package steps

// |@@| F

import (
	"context"
	"gardening/src/dat/maes"
	"gardening/src/lib/error"
	"gardening/src/lib/maestro"
	"gardening/src/srv/fetchers"
	"gardening/src/srv/handlers"
	"gardening/src/srv/molders"
)

type SaveEntityStep struct {
	GardenTaskFetcher          *fetchers.GardenTaskFetcher
	GardenTaskHandler          *handlers.GardenTaskHandler
	Maestro                    *maestro.Maestro
	UpdateGardenTaskFormMolder *molders.UpdateGardenTaskFormMolder
}

func (this *SaveEntityStep) Act(ctx context.Context, in *maes.UpdateGardenTaskMaeIn, out *maes.UpdateGardenTaskMaeOut) (bool, error) {
	var err error
	entity, has, err := this.GardenTaskFetcher.FindOneById(ctx, in.Request.Form.Id, nil)
	if err != nil {
		return false, err
	}
	if !has {
		return false, erro.N("No entity found")
	}
	entity, fields := this.UpdateGardenTaskFormMolder.ToEntity(&in.Request.Form, entity)
	out.Response.GardenTask, err = this.GardenTaskHandler.UpdateFields(ctx, entity, fields, nil)
	if err != nil {
		return false, err
	}
	this.Maestro.AddSuccessMessage(&out.Extra, "Garden Task updated")
	return true, nil
}
