package handlers

import (
	"github.com/fiskerinc/cloud-services/services/attendant/services"
	"encoding/json"

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

func GetAllEccKeys(db *services.DB, id string, data []byte) error {
	logger.Debug().Msgf("GetAllEccKeys %v %s", common.TRex, id)
	var err error
	var eccKeys []common.ECCKeys

	req, err := parseGetAllEccKeysRequest(data)
	if err != nil {
		return err
	}

	if req.CarUpdateID == 0 {
		eccKeys, err = db.GetECCKeys().SelectAllPrivateKeysByVIN(id)
	} else {
		eccKeys, err = db.GetECCKeys().SelectAllPrivateKeysByCarUpdateID(req.CarUpdateID)
	}
	if err != nil {
		return err
	}

	if eccKeys == nil {
		eccKeys = make([]common.ECCKeys, 0)
	}
	eccKeys = replaceECU(eccKeys)

	client := services.RedisClientPool().GetFromPool()
	defer client.Close()

	err = client.SafePublishMessage(common.TRex.Key(id), common.Message{
		Handler: "ecc_keys",
		Data:    eccKeys,
	})

	if err != nil {
		return err
	}

	logger.Debug().Msgf("GetAllEccKeys sent %v %s", common.TRex, id)

	return nil
}

func parseGetAllEccKeysRequest(data []byte) (common.CarUpdateRequest, error) {
	var req common.CarUpdateRequest

	if len(data) == 0 {
		return req, nil
	}

	err := json.Unmarshal(data, &req)
	if err != nil {
		return req, errors.WithStack(err)
	}

	return req, nil
}

func replaceECU(eccKeys []common.ECCKeys) []common.ECCKeys {

	ecuReplacements := common.ECUReplacement()
	for i := 0; i < len(eccKeys); i++ {
		ecu := eccKeys[i].ECU
		if replacement, exist := ecuReplacements[ecu]; exist {
			eccKeys[i].ECU = replacement
		}
	}
	return eccKeys
}

/*
func notifyEccKeysGeneralError(client redis.Client, device common.Device, id string, err error) {
	e := client.PublishMessage(device.Key(id), common.Message{
		Handler: "ecc_keys",
		Data: []struct{ Error string }{
			{
				Error: err.Error(),
			},
		},
	})
	if e != nil {
		logger.Error().Err(errors.WithStack(e)).Send()
	}
}
*/
