// Code generated by eevee. DO NOT EDIT!

package repository

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

	"golang.org/x/xerrors"
)

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

type UserImpl struct {
	userDAO   dao.User
	repo      Repository
	skill     Skill
	userField UserField
	world     World
}

func NewUser(ctx context.Context, tx *sql.Tx) *UserImpl {
	return &UserImpl{
		skill:     NewSkill(ctx, tx),
		userDAO:   dao.NewUser(ctx, tx),
		userField: NewUserField(ctx, tx),
		world:     NewWorld(ctx, tx),
	}
}

func (r *UserImpl) ToModel(value *entity.User) *model.User {
	return r.createCollection(entity.Users{value}).First()
}

func (r *UserImpl) ToModels(values entity.Users) *model.Users {
	return r.createCollection(values)
}

func (r *UserImpl) Create(ctx context.Context, value *entity.User) (*model.User, error) {
	if err := r.userDAO.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 *UserImpl) Creates(ctx context.Context, entities entity.Users) (*model.Users, 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.User) {
		v.SetSavedValue(v.User)
		v.SetAlreadyCreated(true)
	})
	return values, nil
}

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

func (r *UserImpl) create(entity *entity.User, values *model.Users) *model.User {
	value := model.NewUser(entity, r.userDAO)
	r.userField.(*UserFieldImpl).repo = r.repo
	value.UserFields = func(ctx context.Context) (*model.UserFields, error) {
		v, err := values.FindUserFields(ctx, value.ID, r.userField)
		if err != nil {
			return nil, xerrors.Errorf("failed to find user_fields: %w", err)
		}
		return v, nil
	}
	r.skill.(*SkillImpl).repo = r.repo
	value.Skill = func(ctx context.Context) (*model.Skill, error) {
		v, err := values.FindSkill(ctx, value.SkillID, r.skill)
		if err != nil {
			return nil, xerrors.Errorf("failed to find skill: %w", err)
		}
		return v, nil
	}
	r.world.(*WorldImpl).repo = r.repo
	value.World = func(ctx context.Context) (*model.World, error) {
		v, err := values.FindWorld(ctx, value.WorldID, r.world)
		if err != nil {
			return nil, xerrors.Errorf("failed to find world: %w", err)
		}
		return v, nil
	}
	value.SetConverter(r.repo.(model.ModelConverter))
	return value
}
