package thrift

import (
	
	
	
	
)

type flags int16

const (
	enum     flags = 1 << 0
	union    flags = 1 << 1
	required flags = 1 << 2
	optional flags = 1 << 3
	strict   flags = 1 << 4

	featuresBitOffset  = 8
	useDeltaEncoding   = flags(UseDeltaEncoding) << featuresBitOffset
	coalesceBoolFields = flags(CoalesceBoolFields) << featuresBitOffset

	structFlags   flags = enum | union | required | optional
	encodeFlags   flags = strict | protocolFlags
	decodeFlags   flags = strict | protocolFlags
	protocolFlags flags = useDeltaEncoding | coalesceBoolFields
)

func ( flags) ( flags) bool {
	return ( & ) == 
}

func ( flags) ( flags) flags {
	return  & 
}

func ( flags) ( flags) flags {
	return  | 
}

func ( flags) ( flags) flags {
	return  & ^
}

type structField struct {
	typ   reflect.Type
	index []int
	id    int16
	flags flags
}

func forEachStructField( reflect.Type,  []int,  func(structField)) {
	for ,  := 0, .NumField();  < ; ++ {
		 := .Field()

		if .PkgPath != "" && !.Anonymous { // unexported
			continue
		}

		 := append(, )
		 = [:len():len()]

		if .Anonymous {
			 := .Type

			for .Kind() == reflect.Ptr {
				 = .Elem()
			}

			if .Kind() == reflect.Struct {
				(, , )
				continue
			}
		}

		 := .Tag.Get("thrift")
		if  == "" {
			continue
		}
		 := strings.Split(, ",")
		 := flags(0)

		for ,  := range [1:] {
			switch  {
			case "enum":
				 = .with(enum)
			case "union":
				 = .with(union)
			case "required":
				 = .with(required)
			case "optional":
				 = .with(optional)
			default:
				panic(fmt.Errorf("thrift struct field contains an unknown tag option %q in `thrift:\"%s\"`", , ))
			}
		}

		if .have(optional | required) {
			panic(fmt.Errorf("thrift struct field cannot be both optional and required in `thrift:\"%s\"`", ))
		}

		if .have(union) {
			if .Type.Kind() != reflect.Interface {
				panic(fmt.Errorf("thrift union tag found on a field which is not an interface type `thrift:\"%s\"`", ))
			}

			if [0] != "" {
				panic(fmt.Errorf("invalid thrift field id on union field `thrift:\"%s\"`", ))
			}

			(structField{
				typ:   .Type,
				index: ,
				flags: ,
			})
		} else {
			if .have(enum) {
				switch .Type.Kind() {
				case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
				case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
				default:
					panic(fmt.Errorf("thrift enum tag found on a field which is not an integer type `thrift:\"%s\"`", ))
				}
			}

			if ,  := strconv.ParseInt([0], 10, 16);  != nil {
				panic(fmt.Errorf("invalid thrift field id found in struct tag `thrift:\"%s\"`: %w", , ))
			} else if  <= 0 {
				panic(fmt.Errorf("invalid thrift field id found in struct tag `thrift:\"%s\"`: %d <= 0", , ))
			} else {
				(structField{
					typ:   .Type,
					index: ,
					id:    int16(),
					flags: ,
				})
			}
		}
	}
}