// Copyright 2015 Matt T. Proud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package pbtest

import (
	"errors"
	"reflect"

	"github.com/golang/protobuf/proto"
)

var (
	errNotPointer = errors.New("pbtest: cannot sanitize non-pointer message")
	errNotStruct  = errors.New("pbtest: cannot sanitize non-struct message")
)

// SanitizeGenerated empties the private state fields of Protocol Buffer
// messages that have been generated by the testing/quick package or returns
// an error indicating a problem it encountered.
func SanitizeGenerated(m proto.Message) error {
	return sanitizeGenerated(m, 0)
}

func sanitizeGenerated(m proto.Message, l int) error {
	typ := reflect.TypeOf(m)
	if typ.Kind() != reflect.Ptr {
		if l == 0 {
			// Changes cannot be applied to non-pointers.
			return errNotPointer
		}
		return nil
	}
	if elemTyp := typ.Elem(); elemTyp.Kind() != reflect.Struct {
		if l == 0 {
			// Protocol Buffer messages are structures; only they can be cleaned.
			return errNotStruct
		}
		return nil
	}
	elem := reflect.ValueOf(m).Elem()
	for i := 0; i < elem.NumField(); i++ {
		field := elem.Field(i)
		if field.Type().Implements(reflect.TypeOf((*proto.Message)(nil)).Elem()) {
			if err := sanitizeGenerated(field.Interface().(proto.Message), l+1); err != nil {
				return err
			}
		}
		if field.Kind() == reflect.Slice {
			for i := 0; i < field.Len(); i++ {
				elem := field.Index(i)
				if elem.Type().Implements(reflect.TypeOf((*proto.Message)(nil)).Elem()) {
					if err := sanitizeGenerated(elem.Interface().(proto.Message), l+1); err != nil {
						return err
					}
				}
			}
		}
	}
	if field := elem.FieldByName("XXX_unrecognized"); field.IsValid() {
		field.Set(reflect.ValueOf([]byte{}))
	}
	if field := elem.FieldByName("XXX_extensions"); field.IsValid() {
		field.Set(reflect.ValueOf(nil))
	}
	return nil
}
