package relationers

// |@@| C

import (
	"context"
	"gardening/src/lib/relationer"
	"gardening/src/mdl"
	"gardening/src/srv/fetchers"
)

type GardenRelationer struct {
	GardenTaskFetcher *fetchers.GardenTaskFetcher
	PlantationFetcher *fetchers.PlantationFetcher
	Relationer        *relationer.Relationer
}

func (this *GardenRelationer) DistributeGardenTasks(ctx context.Context, set []*mdl.Garden, setToMerge []*mdl.GardenTask) {
	for _, item := range set {
		for _, itemToMerge := range setToMerge {
			if item.Id == itemToMerge.GardenId {
				item.GardenTasks = append(item.GardenTasks, itemToMerge)
			}
		}
	}
}
func (this *GardenRelationer) HydrateGardenTasks(ctx context.Context, set []*mdl.Garden, mod *relationer.RelationerMod) error {
	ids := this.Relationer.GetUniqueEntitiesIds(ctx, this.convertGardensToEntities(set))
	if len(ids) == 0 {
		return nil
	}
	setToMerge, err := this.GardenTaskFetcher.FindSetInGardenIds(ctx, ids, this.Relationer.GetFetcherMod(mod))
	if err != nil {
		return err
	}
	this.DistributeGardenTasks(ctx, set, setToMerge)
	return nil
}
func (this *GardenRelationer) convertGardensToEntities(entities []*mdl.Garden) []relationer.Entity {
	var set []relationer.Entity
	for _, p := range entities {
		set = append(set, p)
	}
	return set
}
func (this *GardenRelationer) DistributePlantations(ctx context.Context, set []*mdl.Garden, setToMerge []*mdl.Plantation) {
	for _, item := range set {
		for _, itemToMerge := range setToMerge {
			if item.Id == itemToMerge.GardenId {
				item.Plantations = append(item.Plantations, itemToMerge)
			}
		}
	}
}
func (this *GardenRelationer) HydratePlantations(ctx context.Context, set []*mdl.Garden, mod *relationer.RelationerMod) error {
	ids := this.Relationer.GetUniqueEntitiesIds(ctx, this.convertGardensToEntities(set))
	if len(ids) == 0 {
		return nil
	}
	setToMerge, err := this.PlantationFetcher.FindSetInGardenIds(ctx, ids, this.Relationer.GetFetcherMod(mod))
	if err != nil {
		return err
	}
	this.DistributePlantations(ctx, set, setToMerge)
	return nil
}
