package database

import (
	"github.com/zeromicro/go-zero/core/mapping"
	"reflect"
)

func InArgs(args interface{}) string {
	bytes := make([]byte, 0)
	bytes = appendIn(bytes, reflect.ValueOf(args))
	return string(bytes)
}

func Arg(args interface{}) string {
	bytes := make([]byte, 0)
	v := reflect.ValueOf(args)
	bytes = appendValue(bytes, v)
	return string(bytes)
}

func appendIn(b []byte, slice reflect.Value) []byte {
	sliceLen := slice.Len()
	b = append(b, '(')
	for i := 0; i < sliceLen; i++ {
		if i > 0 {
			b = append(b, ',')
		}

		elem := slice.Index(i)
		if elem.Kind() == reflect.Interface {
			elem = elem.Elem()
		}
		if elem.Kind() == reflect.Slice {
			//b = appendIn(b, elem)
		} else {
			b = appendValue(b, elem)
		}
	}
	b = append(b, ')')
	return b
}

func appendValue(b []byte, v reflect.Value) []byte {
	if v.Kind() == reflect.Ptr && v.IsNil() {

		return append(b, "NULL"...)
	}
	if v.Kind() == reflect.Int || v.Kind() == reflect.Int64 || v.Kind() == reflect.Float64 {
		return append(b, []byte(mapping.Repr(v.Interface()))...)
	}
	b = append(b, []byte("'")...)
	b = append(b, []byte(mapping.Repr(v.Interface()))...)
	b = append(b, []byte("'")...)
	return b
}