package utils

import (
	"reflect"
	"time"
)

func String2Pointer(value string) *string {
	return &value
}

func Pointer2String(ptr *string) (value string) {
	if ptr != nil {
		value = *ptr
	}
	return value
}

func Int2Pointer(value int) *int {
	return &value
}

func Pointer2Int(ptr *int) (value int) {
	if ptr != nil {
		value = *ptr
	}
	return value
}

func Int64ToPointer(value int64) *int64 {
	return &value
}

func Pointer2Int64(ptr *int64) (value int64) {
	if ptr != nil {
		value = *ptr
	}
	return value
}

func Float32ToPointer(value float32) *float32 {
	return &value
}

func Pointer2Float32(ptr *float32) (value float32) {
	if ptr != nil {
		value = *ptr
	}
	return value
}

func Float64ToPointer(value float64) *float64 {
	return &value
}

func Pointer2Float64(ptr *float64) (value float64) {
	if ptr != nil {
		value = *ptr
	}
	return value
}

func Time2Pointer(value time.Time) (valuePtr *time.Time) {
	if !IsTimeZero(value) {
		valuePtr = &value
	}
	return valuePtr
}

func Pointer2Time(ptr *time.Time) (value time.Time) {
	if ptr != nil {
		value = *ptr
	} else {
		value = DefaultTimeValue
	}
	return value
}

func IsNil(i interface{}) bool {
	defer func() {
		recover()
	}()
	vi := reflect.ValueOf(i)
	switch vi.Kind() {
	case reflect.String:
		return len(i.(string)) == 0
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		return i.(int) == 0
	case reflect.Float32, reflect.Float64:
		return i.(float64) == 0.0
	case reflect.Bool:
		return i.(bool)
	case reflect.Map:
		return len(i.(map[interface{}]interface{})) == 0
	case reflect.Slice:
		return len(i.([]interface{})) == 0
	}
	return vi.IsNil()
}
