package handlers

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

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

// HandleCarSoftwareInformation godoc
// @Summary Get overall software version from a car and its ecu version information
// @Description Get overall software version from a car and its ecu version information
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param vin query string true "VIN"
// @Success 200 {object} CarSoftwareInformationResponse
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /car/software_information [get]
func HandleCarSoftwareInformation(w http.ResponseWriter, r *http.Request) {
	qs := r.URL.Query()
	vin := qs.Get("vin")
	information, err := carSoftwareInformation(vin)
	if loggerdataresp.BadDataError(err) {
		return
	}
	utils.RespJSON(w, http.StatusOK, information)
}

func carSoftwareInformation(vin string) (info CarSoftwareInformationResponse, err error) {
	info.VIN = vin
	var ecus []common.CarECU
	ecus, err = services.GetDB().GetCars().GetCarECUs(common.CarECUFilter{VIN: vin, Unique: true}, nil)
	if err != nil {
		return
	}
	info.ECUVersionInformation = convertCommonCarECUToECUVersionInformationArray(ecus)
	var carVersion common.CarPKCOSVersion
	carVersion, err = services.GetDB().GetCars().GetSoftwareVersion(vin)
	info.OSVersion = carVersion.OSVersion
	info.SUMsVersion = carVersion.SumsVersion
	return
}

type CarSoftwareInformationResponse struct {
	VIN                   string                  `json:"vin"`
	SUMsVersion           string                  `json:"sum_version"`
	OSVersion             string                  `json:"os_version"`
	ECUVersionInformation []ECUVersionInformation `json:"ecu_version_information"`
}

type ECUVersionInformation struct {
	ECU             string `json:"ecu"`
	SoftwareVersion string `json:"software_version"`
	HardwareVersion string `json:"hardware_version"`
}

func convertCommonCarECUToECUVersionInformationArray(input []common.CarECU) (output []ECUVersionInformation) {
	output = make([]ECUVersionInformation, len(input))
	for index, ecuInfo := range input {
		output[index] = convertCommonCarECUToECUVersionInformation(ecuInfo)
	}
	// Probably want to sort the ECU's alphabetically
	return output
}

func convertCommonCarECUToECUVersionInformation(input common.CarECU) (output ECUVersionInformation) {
	output.ECU = input.ECU
	output.SoftwareVersion = input.Version
	output.HardwareVersion = input.HWVersion
	return output
}
