// Code generated by eevee. DO NOT EDIT!

package repository

import (
	"/dao"
	"/entity"
	"/model"
	"context"
	"database/sql"

	"golang.org/x/xerrors"
)

type World interface {
	ToModel(*entity.World) *model.World
	ToModels(entity.Worlds) *model.Worlds
	Create(context.Context, *entity.World) (*model.World, error)
	Creates(context.Context, entity.Worlds) (*model.Worlds, error)
}

type WorldImpl struct {
	worldDAO dao.World
	repo     Repository
}

func NewWorld(ctx context.Context, tx *sql.Tx) *WorldImpl {
	return &WorldImpl{worldDAO: dao.NewWorld(ctx, tx)}
}

func (r *WorldImpl) ToModel(value *entity.World) *model.World {
	return r.createCollection(entity.Worlds{value}).First()
}

func (r *WorldImpl) ToModels(values entity.Worlds) *model.Worlds {
	return r.createCollection(values)
}

func (r *WorldImpl) Create(ctx context.Context, value *entity.World) (*model.World, error) {
	if err := r.worldDAO.Create(ctx, value); err != nil {
		return nil, xerrors.Errorf("cannot Create: %w", err)
	}
	v := r.ToModel(value)
	v.SetSavedValue(value)
	v.SetAlreadyCreated(true)
	return v, nil
}

func (r *WorldImpl) Creates(ctx context.Context, entities entity.Worlds) (*model.Worlds, error) {
	for _, v := range entities {
		if _, err := r.Create(ctx, v); err != nil {
			return nil, xerrors.Errorf("cannot Create: %w", err)
		}
	}
	values := r.ToModels(entities)
	values.Each(func(v *model.World) {
		v.SetSavedValue(v.World)
		v.SetAlreadyCreated(true)
	})
	return values, nil
}

func (r *WorldImpl) createCollection(entities entity.Worlds) *model.Worlds {
	values := model.NewWorlds(entities)
	for i := 0; i < len(entities); i += 1 {
		values.Add(r.create(entities[i], values))
	}
	return values
}

func (r *WorldImpl) create(entity *entity.World, values *model.Worlds) *model.World {
	value := model.NewWorld(entity, r.worldDAO)
	value.SetConverter(r.repo.(model.ModelConverter))
	return value
}
