package utils

import (
	"math"
	"strconv"

	"github.com/AFASystems/presence/internal/pkg/model"
)

func CalculateDistance(adv model.BeaconAdvertisement) float64 {
	rssi := adv.RSSI
	power := adv.TXPower
	ratio := float64(rssi) * (1.0 / float64(twosComp(power)))
	distance := 100.0
	if ratio < 1.0 {
		distance = math.Pow(ratio, 10)
	} else {
		distance = (0.89976)*math.Pow(ratio, 7.7095) + 0.111
	}
	return distance
}

// TwosComp converts a two's complement hexadecimal string to int64
func twosComp(inp string) int64 {
	i, _ := strconv.ParseInt("0x"+inp, 0, 64)
	return i - 256
}

// ValidateRSSI validates if RSSI value is within reasonable bounds
func ValidateRSSI(rssi int64) bool {
	return rssi >= -120 && rssi <= 0
}

// ValidateTXPower validates if TX power is within reasonable bounds
func ValidateTXPower(txPower string) bool {
	power := twosComp(txPower)
	return power >= -128 && power <= 127
}
