package handlers

import (
	"net/http"

	"otaupdate/controllers"
	"otaupdate/services"

	"github.com/fiskerinc/cloud-services/pkg/cache"
	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/db/queries"
	"github.com/fiskerinc/cloud-services/pkg/logger"
	"github.com/fiskerinc/cloud-services/pkg/mongo"
	"github.com/fiskerinc/cloud-services/pkg/validator"

	"github.com/julienschmidt/httprouter"
)

// HandleFleetVehicleGetList godoc
// @Summary Get vehicles for fleet
// @Description Get vehicles for fleet
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param name path string true "Name"
// @Param limit query int false "Max number of records"
// @Param offset query int false "Records offset"
// @Success 200 {object} common.JSONDBQueryResult
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /fleet/{name}/vehicles [get]
func HandleFleetVehicleGetList(w http.ResponseWriter, r *http.Request) {
	fleetVehiclesGetList.Handle(w, r)
}

var fleetVehiclesGetList = controllers.NewMongoGetList(&fleetVehiclesGetListHelper{})

type fleetVehiclesGetListHelper struct{}

func (h *fleetVehiclesGetListHelper) NewModel() interface{} {
	return &mongo.Fleet{}
}

func (h *fleetVehiclesGetListHelper) ParseGetListURLParams(r *http.Request, model interface{}) {
	filter := model.(*mongo.Fleet)

	params := httprouter.ParamsFromContext(r.Context())
	filter.Name = params.ByName("name")

	filter.SetSearchQuery(r.URL.Query().Get("search"))
}

func (h *fleetVehiclesGetListHelper) ParseGetListQueryParams(r *http.Request, model interface{}) {
	// does not utilize URL queries so leave this function empty
}

func (h *fleetVehiclesGetListHelper) ValidateStruct(model interface{}) error {
	result := model.(*mongo.Fleet)

	err := validator.ValidateField(result.Name, "required,fleet")
	if err != nil {
		return controllers.ErrorPKRequired
	}

	return nil
}

func (h *fleetVehiclesGetListHelper) QueryCount(filter interface{}) (int64, error) {
	client, err := services.GetMongoClient()
	if err != nil {
		return 0, err
	}

	f := filter.(*mongo.Fleet)

	return client.GetFleets().GetVehiclesForFleetCount(f.Name, f.SearchQuery())
}

func (h *fleetVehiclesGetListHelper) QuerySelect(filter interface{}, options *queries.PageQueryOptions) (interface{}, error) {
	client, err := services.GetMongoClient()
	if err != nil {
		return nil, err
	}

	f := filter.(*mongo.Fleet)

	vins, err := client.GetFleets().GetVehiclesForFleet(f.Name, f.SearchQuery(), options)
	if err != nil {
		return nil, err
	}

	var response []fleetVehicle

	// get CarUpdate
	carUpdates := services.GetDB().GetCarUpdates()
	ups, _ := carUpdates.SelectMostRecentByVINs(vins)

	// setup CarState
	clientPool := services.RedisClientPool()

	// merge Vin, CarUpdate, CarState
	parser := cache.NewVehicleState(clientPool)
	for _, vin := range vins {
		state, err := parser.Get(vin)
		if err != nil {
			state = common.CarState{}
			logger.Warn().Err(err).Send()
		}

		vehicle := fleetVehicle{
			VIN:       vin,
			CarState:  &state,
			CarUpdate: &common.CarUpdate{},
		}

		for _, carUpdate := range ups {
			if carUpdate.VIN == vin {
				vehicle.CarUpdate = &carUpdate
				break
			}
		}
		response = append(response, vehicle)
	}

	return response, err
}

type fleetVehicle struct {
	VIN       string            `json:"vin" validate:"required,vin"`
	CarState  *common.CarState  `json:"carstate"`
	CarUpdate *common.CarUpdate `json:"carupdate,omitempty"`
}
