package encoder

import (
	
	
	
	

	
	
	
	
)

// The embedded fallback of a struct of the v2 semantics: a field of a map of string keys or of jsontext.Value,
// whose members are members of the JSON object of the struct, after the members of its fields. It is encoded by
// a field of its own at the end of the struct, which writes no key: its value writes the members, followed by the
// comma after them which the field writes, or takes back the comma before them if there is none.

// fallback is the embedded fallback of a struct.
type fallback struct {
	root  reflect.Type // the struct whose address the field is given
	index []int        // the index of the fallback in it, by reflect.Type.FieldByIndex
	raw   bool         // whether it is jsontext.Value, or a map
	// names are the names of the members of the fields, which a name of the fallback may not be: by their exact
	// names, and by their folded names ( see jsonfields.FoldName ) in their breadth-first order. caseIgnore is
	// whether a field matches by its folded name ( case:ignore ) without MatchCaseInsensitiveNames.
	names      map[string]*jsonfields.Field
	folded     map[string][]*jsonfields.Field
	caseIgnore bool
}

// v2FallbackField returns the field of the embedded fallback of the struct typ, whose members are fields.
func ( *Compiler) ( reflect.Type,  *jsonfields.Fields) *StructFieldCode {
	 := &fallback{
		root:   ,
		index:  .Fallback.Index,
		raw:    indirectOf(.Fallback.Type) == jsonfields.RawValueType,
		names:  map[string]*jsonfields.Field{},
		folded: map[string][]*jsonfields.Field{},
	}
	for  := range .List {
		 := &.List[]
		.names[.Name] = 
		 := string(jsonfields.FoldName([]byte(.Name)))
		.folded[] = append(.folded[], )
		.caseIgnore = .caseIgnore || .Casing&jsonfields.CaseIgnore != 0
	}
	for ,  := range .folded {
		slices.SortFunc(, func(,  *jsonfields.Field) int { return .ID - .ID })
	}
	var  reflect.Type
	if !.raw {
		 = indirectOf(.Fallback.Type).Elem()
	}
	return &StructFieldCode{
		typ:        ,
		tag:        &runtime.StructTag{},
		isFallback: true,
		value: .appendFuncCode(, func( *RuntimeContext,  []byte,  unsafe.Pointer) ([]byte, error) {
			return .appendMembers(, , , )
		}),
	}
}

func indirectOf( reflect.Type) reflect.Type {
	if .Kind() == reflect.Pointer && .Name() == "" {
		return .Elem()
	}
	return 
}

// appendMembers appends the members of the fallback of the struct at p, after b, which ends with the comma after
// the last member of the struct, or with the brace which begins the object.
func ( *fallback) ( *RuntimeContext,  []byte,  unsafe.Pointer,  reflect.Type) ([]byte, error) {
	// a nil pointer on the way to the fallback, or to it, is no member.
	,  := reflect.NewAt(.root, ).Elem().FieldByIndexErr(.index)
	 :=  == nil
	if  && .Kind() == reflect.Pointer {
		 = !.IsNil()
		if  {
			 = .Elem()
		}
	}
	 := 
	if  && .Len() > 0 {
		// the members of the map or the raw value, which an empty one has none of.
		var  func( []byte) bool
		if .Option.Flag&AllowDuplicateNamesOption == 0 {
			 := &fallbackNames{
				fb: , before: , others: .raw || .RescanNames,
				flags: .Option.Flag,
			}
			 = .insertName
		}
		if .raw {
			,  = V2Hooks.AppendRawMembers(, , .Bytes(), )
		} else {
			,  = .appendMapMembers(, , , , )
		}
		if  != nil {
			return , 
		}
	}
	// the comma after the members is written by the field, which takes back the one before them if none is.
	if [len()-1] == ',' {
		 = [:len()-1]
		.Rewrote(len())
	}
	return , nil
}

// fallbackNames decides which names of the members of a fallback may be written: neither the name of a member
// which is written already, of the object which before is in, nor the name of another member of the fallback.
//
// Most names are none of the names of the fields of the struct, which the names of the fallback are found in
// first: the members of the fields which the object has are read from its output only for a name of a field,
// which is written or was omitted. The names of the fallback itself are kept only where two of them can be the
// same: the members of a jsontext.Value, and the keys of a map, which are unique, but whose names are the same if
// the bytes of their invalid UTF-8 are written as U+FFFD ( see RuntimeContext.RescanNames ).
type fallbackNames struct {
	fb     *fallback
	before []byte
	// flags are the options of the encoding, of which MatchCaseInsensitiveNamesOption and
	// MatchCaseSensitiveDelimiterOption match the names, and others is whether the names of the fallback are kept.
	flags  OptionFlag
	others bool
	// written are the fields whose members are written, read from before when a name is the one of a field, and
	// otherNames the names of the fallback which are no field's.
	written    map[*jsonfields.Field]bool
	otherNames map[string]bool
}

// insertName records that the member of the fallback of the name is written, and reports whether it may be: the
// name is neither one which is written already nor, if the names of the fallback are kept, one of the fallback
// before it.
func ( *fallbackNames) ( []byte) bool {
	 := .fb
	if  := .names[string()];  != nil {
		return .insertField()
	}
	if  := .flags&MatchCaseInsensitiveNamesOption != 0; .caseIgnore ||  {
		for ,  := range .folded[string(jsonfields.FoldName())] {
			if (.Casing&jsonfields.CaseIgnore != 0 || ( && .Casing&jsonfields.CaseStrict == 0)) &&
				(.flags&MatchCaseSensitiveDelimiterOption == 0 || strings.EqualFold(string(), .Name)) {
				return .insertField()
			}
		}
	}
	if !.others {
		return true
	}
	if .otherNames == nil {
		.otherNames = map[string]bool{}
	} else if .otherNames[string()] {
		return false
	}
	.otherNames[string()] = true
	return true
}

// insertField records that the member of f is written, and reports whether it was not: the members of the fields
// which the object has are read from its output the first time.
func ( *fallbackNames) ( *jsonfields.Field) bool {
	if .written == nil {
		.written = .writtenFields()
	}
	if .written[] {
		return false
	}
	.written[] = true
	return true
}

// writtenFields returns the fields whose members the object which the output before is in has.
func ( *fallbackNames) () map[*jsonfields.Field]bool {
	 := map[*jsonfields.Field]bool{}
	 := .before[enclosingObjectStart(.before):]
	for ,  := range memberNames(append([:len():len()], '}')) {
		 := stringEnd(, )
		 := jsonstring.AppendUnescaped(nil, [+1:])
		if  := .fb.names[string()];  != nil {
			[] = true
		}
	}
	return 
}

// enclosingObjectStart returns where the object starts which the output b, compact and valid, is in: the
// brace before it which no other value contains.
func enclosingObjectStart( []byte) int {
	 := 0
	for  := len() - 1;  >= 0; -- {
		switch [] {
		case '"':
			 = stringStart(, )
		case '}', ']':
			++
		case '{', '[':
			if  == 0 {
				return 
			}
			--
		}
	}
	return 0
}

// appendMapMembers appends the entries of the map m, of string keys, as members, by the order of the keys if the
// output is deterministic.
func ( *fallback) ( *RuntimeContext,  []byte,  reflect.Value,  reflect.Type,  func([]byte) bool) ([]byte, error) {
	if .Len() == 0 {
		return , nil
	}
	 := .MapKeys()
	if .Option.Flag&UnorderedMapOption == 0 {
		slices.SortFunc(, func(,  reflect.Value) int {
			return strings.Compare(.String(), .String())
		})
	}
	 := reflect.New().Elem()
	for ,  := range  {
		 := 
		,  := appendName(, , .String())
		if  != nil {
			// a name of invalid UTF-8, which is reported for the type of the key.
			return , &errors.SemanticError{GoType: .Type(), Err: errors.ErrInvalidUTF8}
		}
		if  != nil {
			 := jsonstring.AppendUnescaped(nil, [len()+1:len()-1])
			if !() {
				return , &errors.TextError{Err: errors.ErrDuplicateName, Name: string(), Out: , AtDelim: true}
			}
		}
		 = append(, ':')
		.Set(.MapIndex())
		,  = appendValueOf(, , , .Addr().UnsafePointer())
		if  != nil {
			return , 
		}
		 = append(, ',')
	}
	return , nil
}

// appendValueOf appends the value at p, of typ, by its opcodes, which run in a context of their own, as the ones of
// a default representation do ( see appendDefault ).
func appendValueOf( *RuntimeContext,  []byte,  reflect.Type,  unsafe.Pointer) ([]byte, error) {
	,  := compileValueOf(, )
	if  != nil {
		return , 
	}
	return runInner(, , , )
}

// compileValueOf returns the opcodes of a value of typ for the options of ctx.
func compileValueOf( *RuntimeContext,  reflect.Type) (*OpcodeSet, error) {
	if .Option.Flag&MarshalFuncsOption != 0 {
		return .Option.Funcs.codeSet(uintptr(runtime.TypePtr()), .compileMode())
	}
	return compileToGetUnfilteredCodeSet(uintptr(runtime.TypePtr()), .compileMode())
}