package handlers

import (
	"fmt"
	"net/http"
	"otaupdate/services"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/httphandlers"
	re "github.com/fiskerinc/cloud-services/pkg/redis"
	rutils "github.com/fiskerinc/cloud-services/pkg/redis/redisutils"
	"github.com/fiskerinc/cloud-services/pkg/utils"

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

// HandleVehicleConnectionStatuses godoc
// @Summary Gets connection statuses car vins
// @Description Returns hash object of car connection statuses
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param vins body common.VINs true "VINs"
// @Success 200 {object} map[string]bool "Car update statuses"
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /carsconnected [post]
func HandleVehicleConnectionStatuses(w http.ResponseWriter, r *http.Request) {
	var request common.VINs
	err := httphandlers.ParseRequest(r, &request)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	count := len(request.VINs)

	conn := services.RedisClientPool().GetFromPool()
	defer conn.Close()
	cars, err := rutils.CheckSet(conn, re.CarSessionsKey(), request.VINs)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		return
	}

	if len(cars) != count {
		err = errors.New("returned statuses not equal in length to vins")
		loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable)
		return
	}

	hmis, err := rutils.CheckSet(conn, re.HMISessionsKey(), request.VINs)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		return
	}

	if len(hmis) != count {
		err = errors.New("returned HMI statuses not equal in length to vins")
		loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable)
		return
	}

	result := make(map[string]bool, count*2)
	for i, vin := range request.VINs {
		result[vin] = cars[i]
		result[fmt.Sprintf("2:%s", vin)] = hmis[i]
	}

	utils.RespJSON(w, http.StatusOK, result)
}

type CarConnectionStatus struct {
	VIN       string `json:"vin"`
	Connected bool   `json:"connected"`
}
