package ii

import (
	"git.simanc.com/software/golib/v4/features/mo"
	"git.simanc.com/software/golib/v4/pkg/tuid"
)

func (f *FieldInfo) getFields() []*FieldInfo {
	fields := make([]*FieldInfo, len(f.Fields))
	for i := range f.Fields {
		fields[i] = &f.Fields[i]
	}
	return fields
}

func (f *FieldInfo) DefaultValue() any {
	switch f.Default {
	case internalNow:
		if f.Type == mo.TypeDateTime {
			return mo.NewDateTime()
		} else {
			return f.defaultValue
		}
	case internalNew:
		switch f.Type {
		case mo.TypeObjectId:
			return mo.ID.New()
		case mo.TypeString:
			return tuid.UID()
		}
		fallthrough
	default:
		return f.defaultValue
	}
}

func (f *FieldInfo) EnumsValue() mo.A {
	enum := make(mo.A, len(f.enums))
	for i, e := range f.enums {
		enum[i] = e
	}
	return enum
}

func (f *FieldInfo) SubField(name string) (FieldInfo, bool) {
	for _, field := range f.Fields {
		if field.Name == name {
			return field, true
		}
	}
	return FieldInfo{}, false
}

func (f *FieldInfo) ValidateJSON() (j FieldInfoJSON) {
	j.Name = f.Name
	j.Label = f.Label
	j.Type = f.Type.String()
	j.Required = f.Required
	j.Unique = f.Unique
	j.Minimum = f.Minimum
	j.Maximum = f.Maximum
	j.Decimal = f.Decimal
	j.Default = f.DefaultValue()
	j.Enums = f.EnumsValue()
	j.Pattern = f.Pattern
	j.Fields = make([]FieldInfoJSON, len(f.Fields))
	for i, subField := range f.Fields {
		j.Fields[i] = subField.ValidateJSON()
	}
	return
}
