package handlers

import (
	"github.com/fiskerinc/cloud-services/services/depot/services"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/logger"
	"github.com/fiskerinc/cloud-services/pkg/redis"
)

func MobileInit(db *services.DB, id string) error {
	client := services.RedisClientPool().GetFromPool()
	defer client.Close()

	err := addMobileSession(client, id)
	if err != nil {
		logger.Warn().Str("id", id).Err(err).Send()
	}

	carDrivers, err := db.GetCars().GetCarsForDriver(id)
	if err != nil {
		logger.Error().Msgf("can not load cars for driver %v", err)
		return err
	}

	for _, carDriver := range carDrivers {
		sendSettingsMobile(client, db, carDriver.VIN, id)
		// If we fail to send the digital twin, it is not a major problem
		sendFullDigitalTwinToMobile(carDriver.VIN, id)
	}

	return nil
}

func addMobileSession(client redis.Client, id string) error {
	_, err := client.Execute("SADD", redis.MobileSessionsKey(), id)
	return err
}

func sendSettingsMobile(client redis.Client, db *services.DB, vin, driverID string) error {
	settings, err := getSettings(db, vin)
	if err != nil {
		return err
	}

	return client.SafePublishMessage(common.Mobile.Key(driverID),
		common.Message{
			Handler: "car_settings",
			Data:    settings,
		},
	)
}

func sendFullDigitalTwinToMobile(vin string, driverID string) (err error) {
	err = services.GetSendDigitalTwin().SendToDriver(vin, driverID)
	if err != nil {
		logger.Err(err).Str("VIN", vin).Str("Driver ID", driverID).Msg("Failed to Send Full Digital Twin to Mobile Connection on INIT")
	}
	return
}
