package sdb

import (
	"errors"
)

var (
	errKeyNotFound = errors.New("key not found")
)

type M map[string]any

func (m M) Int64(k string) int64 {
	v, ok := m[k].(int64)
	if !ok {
		return int64(m.Float64(k))
	}
	return v
}

func (m M) MustInt64(k string) int64 {
	if _, ok := m[k]; !ok {
		panic(errKeyNotFound)
	}
	return m.Int64(k)
}

func (m M) String(k string) string {
	v, ok := m[k].(string)
	if !ok {
		return ""
	}
	return v
}

func (m M) MustString(k string) string {
	if _, ok := m[k]; !ok {
		panic(errKeyNotFound)
	}
	return m.String(k)
}

func (m M) Any(k string) any {
	v, _ := m[k]
	return v
}

func (m M) MustAny(k string) any {
	if _, ok := m[k]; !ok {
		panic(errKeyNotFound)
	}
	return m.Any(k)
}

func (m M) Float64(k string) float64 {
	v, ok := m[k].(float64)
	if !ok {
		return 0
	}
	return v
}

func (m M) MustFloat64(k string) float64 {
	if _, ok := m[k]; !ok {
		panic(errKeyNotFound)
	}
	return m.Float64(k)
}

func (m M) Bool(k string) bool {
	v, ok := m[k].(bool)
	if !ok {
		return false
	}
	return v
}

func (m M) MustBool(k string) bool {
	if _, ok := m[k]; !ok {
		panic(errKeyNotFound)
	}
	return m.Bool(k)
}

func (m M) Uint(k string) uint64 {
	v, ok := m[k].(uint64)
	if !ok {
		return uint64(m.Int64(k))
	}
	return v
}

func (m M) MustUint(k string) uint64 {
	if _, ok := m[k]; !ok {
		panic(errKeyNotFound)
	}
	return m.Uint(k)
}
