package cachev2

import (
	"context"
	"errors"

	"github.com/fiskerinc/cloud-services/pkg/common"
	redis "github.com/fiskerinc/cloud-services/pkg/redisv2"
	"github.com/fiskerinc/cloud-services/pkg/utils/elptr"
)

func GetTowManDigitalTwin(vin string, redisClient *redis.Connection)(tdt common.TowmanDigitalTwin, err error){
	// TODO: Make this more efficient with specific gets
	dTwins, errorList := GetVINListDigitalTwin([]string{vin}, redisClient)
	if len(errorList) > 0 {
		err = errorList[0]
	}
	if err != nil {
		return
	}

	digitalTwin, ok := dTwins[vin]
	if !ok {
		err = errors.New("digital twin not found")
		return
	}

	tdt.Gear = digitalTwin.GetGear()
	tdt.Location = digitalTwin.GetLocation()
	tdt.Online = digitalTwin.Online
	tdt.Charging = elptr.ElPtr((digitalTwin.GetVCU0x260().ChargeType != "initial_value") && (digitalTwin.GetVCU0x260().ChargeType != ""))

	return
}

func GetVehicleLocation(vin string, redisClient *redis.Connection)(location common.Location, err error){
	res := redisClient.HGet(context.Background(), redis.CarLocationsKey(), vin)
	err = res.Scan(&location)
	return
}