package relationers

// |@@| C

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

type GardenTaskRelationer struct {
	GardenFetcher     *fetchers.GardenFetcher
	PlantationFetcher *fetchers.PlantationFetcher
	Relationer        *relationer.Relationer
}

func (this *GardenTaskRelationer) DistributeGarden(ctx context.Context, set []*mdl.GardenTask, setToMerge []*mdl.Garden) {
	m := make(map[string]*mdl.Garden)
	for _, itemToMerge := range setToMerge {
		m[itemToMerge.Id] = itemToMerge
	}
	for _, item := range set {
		itemToMerge := m[item.GardenId]
		item.Garden = itemToMerge
	}
}
func (this *GardenTaskRelationer) HydrateGarden(ctx context.Context, set []*mdl.GardenTask, mod *relationer.RelationerMod) error {
	ids := this.GetGardenIds(ctx, set)
	if len(ids) == 0 {
		return nil
	}
	setToMerge, err := this.GardenFetcher.FindSetIn(ctx, ids, this.Relationer.GetFetcherMod(mod))
	if err != nil {
		return err
	}
	this.DistributeGarden(ctx, set, setToMerge)
	return nil
}
func (this *GardenTaskRelationer) GetGardenIds(ctx context.Context, set []*mdl.GardenTask) []string {
	return this.Relationer.GetUniqueIds(ctx, func() []string {
		var ids []string
		for _, item := range set {
			ids = append(ids, item.GardenId)
		}
		return ids
	})
}
func (this *GardenTaskRelationer) DistributePlantation(ctx context.Context, set []*mdl.GardenTask, setToMerge []*mdl.Plantation) {
	m := make(map[string]*mdl.Plantation)
	for _, itemToMerge := range setToMerge {
		m[itemToMerge.Id] = itemToMerge
	}
	for _, item := range set {
		itemToMerge := m[item.PlantationId]
		item.Plantation = itemToMerge
	}
}
func (this *GardenTaskRelationer) HydratePlantation(ctx context.Context, set []*mdl.GardenTask, mod *relationer.RelationerMod) error {
	ids := this.GetPlantationIds(ctx, set)
	if len(ids) == 0 {
		return nil
	}
	setToMerge, err := this.PlantationFetcher.FindSetIn(ctx, ids, this.Relationer.GetFetcherMod(mod))
	if err != nil {
		return err
	}
	this.DistributePlantation(ctx, set, setToMerge)
	return nil
}
func (this *GardenTaskRelationer) GetPlantationIds(ctx context.Context, set []*mdl.GardenTask) []string {
	return this.Relationer.GetUniqueIds(ctx, func() []string {
		var ids []string
		for _, item := range set {
			ids = append(ids, item.PlantationId)
		}
		return ids
	})
}
