package util

import (
	"errors"

	"github.com/ngaut/log"
)

// SimpleMap is a map from interface{} to interface{}
type SimpleMap map[string]interface{}

// GetString get a string from a SimpleMap
func (m SimpleMap) GetString(key string) *string {
	rawValue, ok := m[key]
	if !ok {
		log.Errorf("Config format error: %s is not set", key)
		return nil
	}
	value, ok := rawValue.(string)
	if !ok {
		log.Errorf("Config format error: %s is not a string", key)
		return nil
	}
	return &value
}

// GetSimpleMap turn configPtr into a SimpleMap
func GetSimpleMap(configPtr *interface{}) (SimpleMap, error) {
	if configPtr == nil {
		return nil, errors.New("config is nil")
	}
	rawConfig, ok := (*configPtr).(map[string]interface{})
	if !ok {
		return nil, errors.New("Config format error: config is not a map")
	}
	return SimpleMap(rawConfig), nil
}

// GetInt64 get a int from a SimpleMap
func (m SimpleMap) GetInt64(key string) *int64 {
	rawValue, ok := m[key]
	if !ok {
		log.Errorf("Config format error: %s is not set", key)
		return nil
	}

	value, ok := rawValue.(int64)

	if !ok {
		log.Errorf("Config format error: %s is not an int64", key)
		return nil
	}
	return &value
}
