package util

import (
	"encoding/json"
	"fmt"
	"strconv"
)

type FlexibleType string

func (ft *FlexibleType) UnmarshalJSON(data []byte) error {
	var v interface{}
	if err := json.Unmarshal(data, &v); err != nil {
		return err
	}

	switch val := v.(type) {
	case string:
		*ft = FlexibleType(val)
	case float64:
		*ft = FlexibleType(strconv.FormatFloat(val, 'f', -1, 64))
	case bool:
		*ft = FlexibleType(strconv.FormatBool(val))
	default:
		*ft = FlexibleType(fmt.Sprintf("%v", val))
	}
	return nil
}

func (ft FlexibleType) Int() int {
	if ft == "" {
		return 0
	}

	i, _ := strconv.Atoi(string(ft))
	return i
}
