package steps

// |@@| F

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

type SaveEntityStep struct {
	FilesUploader          *uploader.FilesUploader
	GardenFetcher          *fetchers.GardenFetcher
	GardenHandler          *handlers.GardenHandler
	Maestro                *maestro.Maestro
	UpdateGardenFormMolder *molders.UpdateGardenFormMolder
}

func (this *SaveEntityStep) Act(ctx context.Context, in *maes.UpdateGardenMaeIn, out *maes.UpdateGardenMaeOut) (bool, error) {
	var err error
	entity, has, err := this.GardenFetcher.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.UpdateGardenFormMolder.ToEntity(&in.Request.Form, entity)
	this.manageUpload(ctx, in, out, entity)
	out.Response.Garden, err = this.GardenHandler.UpdateFields(ctx, entity, fields, nil)
	if err != nil {
		return false, err
	}
	this.Maestro.AddSuccessMessage(&out.Extra, "Garden updated")
	return true, nil
}
func (this *SaveEntityStep) manageUpload(ctx context.Context, in *maes.UpdateGardenMaeIn, out *maes.UpdateGardenMaeOut, entity *mdl.Garden) {
	if in.Request.Files.Picture != "" {
		entity.Picture = this.FilesUploader.Upload(ctx, in.Request.Files.Picture)
	}
}
