package relationers

// |@@| C

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

type PlantRelationer struct {
	PlantTaskFetcher   *fetchers.PlantTaskFetcher
	PlantationFetcher  *fetchers.PlantationFetcher
	Relationer         *relationer.Relationer
	SeedProgramFetcher *fetchers.SeedProgramFetcher
}

func (this *PlantRelationer) DistributePlantTasks(ctx context.Context, set []*mdl.Plant, setToMerge []*mdl.PlantTask) {
	for _, item := range set {
		for _, itemToMerge := range setToMerge {
			if item.Id == itemToMerge.PlantId {
				item.PlantTasks = append(item.PlantTasks, itemToMerge)
			}
		}
	}
}
func (this *PlantRelationer) HydratePlantTasks(ctx context.Context, set []*mdl.Plant, mod *relationer.RelationerMod) error {
	ids := this.Relationer.GetUniqueEntitiesIds(ctx, this.convertPlantsToEntities(set))
	if len(ids) == 0 {
		return nil
	}
	setToMerge, err := this.PlantTaskFetcher.FindSetInPlantIds(ctx, ids, this.Relationer.GetFetcherMod(mod))
	if err != nil {
		return err
	}
	this.DistributePlantTasks(ctx, set, setToMerge)
	return nil
}
func (this *PlantRelationer) convertPlantsToEntities(entities []*mdl.Plant) []relationer.Entity {
	var set []relationer.Entity
	for _, p := range entities {
		set = append(set, p)
	}
	return set
}
func (this *PlantRelationer) DistributePlantations(ctx context.Context, set []*mdl.Plant, setToMerge []*mdl.Plantation) {
	for _, item := range set {
		for _, itemToMerge := range setToMerge {
			if item.Id == itemToMerge.PlantId {
				item.Plantations = append(item.Plantations, itemToMerge)
			}
		}
	}
}
func (this *PlantRelationer) HydratePlantations(ctx context.Context, set []*mdl.Plant, mod *relationer.RelationerMod) error {
	ids := this.Relationer.GetUniqueEntitiesIds(ctx, this.convertPlantsToEntities(set))
	if len(ids) == 0 {
		return nil
	}
	setToMerge, err := this.PlantationFetcher.FindSetInPlantIds(ctx, ids, this.Relationer.GetFetcherMod(mod))
	if err != nil {
		return err
	}
	this.DistributePlantations(ctx, set, setToMerge)
	return nil
}
func (this *PlantRelationer) DistributeSeedPrograms(ctx context.Context, set []*mdl.Plant, setToMerge []*mdl.SeedProgram) {
	for _, item := range set {
		for _, itemToMerge := range setToMerge {
			if item.Id == itemToMerge.PlantId {
				item.SeedPrograms = append(item.SeedPrograms, itemToMerge)
			}
		}
	}
}
func (this *PlantRelationer) HydrateSeedPrograms(ctx context.Context, set []*mdl.Plant, mod *relationer.RelationerMod) error {
	ids := this.Relationer.GetUniqueEntitiesIds(ctx, this.convertPlantsToEntities(set))
	if len(ids) == 0 {
		return nil
	}
	setToMerge, err := this.SeedProgramFetcher.FindSetInPlantIds(ctx, ids, this.Relationer.GetFetcherMod(mod))
	if err != nil {
		return err
	}
	this.DistributeSeedPrograms(ctx, set, setToMerge)
	return nil
}
