// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package jsonutil

import (
	"encoding/json"
	"fmt"
	"reflect"
	"strings"
	"unsafe"
)

// MarshalJSON returns a JSON encoding of schema containing only selected fields.
// A field is selected if any of the following is true:
//   * it has a non-empty value
//   * its field name is present in forceSendFields and it is not a nil pointer or nil interface
//   * its field name is present in nullFields.
// The JSON key for each selected field is taken from the field's json: struct tag.
func MarshalJSON(schema interface{}, forceSendFields, nullFields []string) ([]byte, error) {
	mustInclude := make(map[string]struct{})
	for _, f := range forceSendFields {
		mustInclude[f] = struct{}{}
	}

	useNull := make(map[string]struct{})
	for _, f := range nullFields {
		useNull[f] = struct{}{}
	}

	dataMap, err := schemaToMap(schema, mustInclude, useNull)
	if err != nil {
		return nil, err
	}

	return json.Marshal(dataMap)
}

func schemaToMap(schema interface{}, mustInclude, useNull map[string]struct{}) (map[string]interface{}, error) {
	m := make(map[string]interface{})
	s := reflect.ValueOf(schema)
	st := s.Type()

	for i := 0; i < s.NumField(); i++ {
		sv := s.Field(i)
		sf := st.Field(i)

		isUnexported := sf.PkgPath != ""
		if sf.Anonymous {
			t := sf.Type
			if t.Kind() == reflect.Ptr {
				t = t.Elem()
			}
			if isUnexported && t.Kind() != reflect.Struct {
				// Ignore embedded fields of unexported non-struct types.
				continue
			}

			// Allow access to unexported fields by creating an addressable copy.
			sfe := reflect.New(sf.Type).Elem()
			sfe.Set(sv)

			// Get a copy of `forceSendFields` slice.
			var forceSendFields []string
			if f := sfe.FieldByName("forceSendFields"); f.IsValid() {
				i := reflect.NewAt(f.Type(), unsafe.Pointer(f.UnsafeAddr())).Elem().Interface()
				if v, ok := i.([]string); ok {
					forceSendFields = v
				}
			}

			// Get a copy of `nullFields` slice.
			var nullFields []string
			if f := sfe.FieldByName("nullFields"); f.IsValid() {
				i := reflect.NewAt(f.Type(), unsafe.Pointer(f.UnsafeAddr())).Elem().Interface()
				if v, ok := i.([]string); ok {
					nullFields = v
				}
			}

			// Marshal the embedded field.
			b, err := MarshalJSON(sv.Interface(), forceSendFields, nullFields)
			if err != nil {
				return nil, fmt.Errorf("failed to marshal anonymous field %q: %v", sf.Name, err)
			}

			// Append all fields to the output map.
			im := make(map[string]interface{})
			json.Unmarshal(b, &im)
			for k, v := range im {
				m[k] = v
			}

			// Nothing else to do.
			continue
		} else if isUnexported {
			// Ignore unexported non-embedded fields.
			continue
		}

		jsonTag := sf.Tag.Get("json")
		if jsonTag == "" {
			continue
		}

		tag, err := parseJSONTag(jsonTag)
		if err != nil {
			return nil, err
		}
		if tag.ignore {
			continue
		}

		if _, ok := useNull[sf.Name]; ok {
			if !isEmptyValue(sv) {
				return nil, fmt.Errorf("field %q in `nullFields` has non-empty value", sf.Name)
			}
			m[tag.apiName] = nil
			continue
		}
		if !includeField(sv, sf, mustInclude) {
			continue
		}

		// nil maps are treated as empty maps.
		if sf.Type.Kind() == reflect.Map && sv.IsNil() {
			m[tag.apiName] = map[string]string{}
			continue
		}

		// nil slices are treated as empty slices.
		if sf.Type.Kind() == reflect.Slice && sv.IsNil() {
			m[tag.apiName] = []bool{}
			continue
		}

		if tag.stringFormat {
			m[tag.apiName] = formatAsString(sv, sf.Type.Kind())
		} else {
			m[tag.apiName] = sv.Interface()
		}
	}

	return m, nil
}

// formatAsString returns a string representation of v, dereferencing it first if possible.
func formatAsString(v reflect.Value, kind reflect.Kind) string {
	if kind == reflect.Ptr && !v.IsNil() {
		v = v.Elem()
	}

	return fmt.Sprintf("%v", v.Interface())
}

// jsonTag represents a restricted version of the struct tag format used by encoding/json.
// It is used to describe the JSON encoding of fields in a Schema struct.
type jsonTag struct {
	apiName      string
	stringFormat bool
	ignore       bool
}

// parseJSONTag parses a restricted version of the struct tag format used by encoding/json.
// The format of the tag must match that generated by the Schema.writeSchemaStruct method
// in the api generator.
func parseJSONTag(val string) (*jsonTag, error) {
	if val == "-" {
		return &jsonTag{ignore: true}, nil
	}

	i := strings.Index(val, ",")
	if i == -1 || val[:i] == "" {
		return nil, fmt.Errorf("malformed json tag: %s", val)
	}

	tag := &jsonTag{
		apiName: val[:i],
	}

	switch val[i+1:] {
	case "omitempty":
	case "omitempty,string":
		tag.stringFormat = true
	default:
		return nil, fmt.Errorf("malformed json tag: %s", val)
	}

	return tag, nil
}

// Reports whether the struct field "f" with value "v" should be included in JSON output.
func includeField(v reflect.Value, f reflect.StructField, mustInclude map[string]struct{}) bool {
	// The regular JSON encoding of a nil pointer is "null", which means "delete this field".
	// Therefore, we could enable field deletion by honoring pointer fields' presence in the mustInclude set.
	// However, many fields are not pointers, so there would be no way to delete these fields.
	// Rather than partially supporting field deletion, we ignore mustInclude for nil pointer fields.
	// Deletion will be handled by a separate mechanism.
	if f.Type.Kind() == reflect.Ptr && v.IsNil() {
		return false
	}

	// The "any" type is represented as an interface{}.  If this interface
	// is nil, there is no reasonable representation to send.  We ignore
	// these fields, for the same reasons as given above for pointers.
	if f.Type.Kind() == reflect.Interface && v.IsNil() {
		return false
	}

	_, ok := mustInclude[f.Name]
	return ok || !isEmptyValue(v)
}

// isEmptyValue reports whether v is the empty value for its type.  This
// implementation is based on that of the encoding/json package, but its
// correctness does not depend on it being identical. What's important is that
// this function return false in situations where v should not be sent as part
// of a PATCH operation.
func isEmptyValue(v reflect.Value) bool {
	switch v.Kind() {
	case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
		return v.Len() == 0
	case reflect.Bool:
		return !v.Bool()
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return v.Int() == 0
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return v.Uint() == 0
	case reflect.Float32, reflect.Float64:
		return v.Float() == 0
	case reflect.Interface, reflect.Ptr:
		return v.IsNil()
	}
	return false
}
