package handlers

import (
	"net/http"

	"github.com/fiskerinc/cloud-services/pkg/httphandlers"
	"github.com/fiskerinc/cloud-services/pkg/validator"

	"otaupdate/controllers"
	"otaupdate/services"

	"github.com/fiskerinc/cloud-services/pkg/common"

	"github.com/julienschmidt/httprouter"
	"github.com/pkg/errors"
)

// HandleVehicleFilterUpdate godoc
// @Summary Update a vehicle filter
// @Description Update a vehicle filter
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param vin path string true "VIN"
// @Param id path string true "CAN ID"
// @Param config body VehicleFilterRequest true "Vehicle filter data"
// @Success 200 {object} common.SubscriptionConfiguration
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /vehicle/{vin}/filter/{id} [put]
func HandleVehicleFilterUpdate(w http.ResponseWriter, r *http.Request) {
	vehicleFilterUpdate.Handle(w, r)
}

var vehicleFilterUpdate = controllers.NewMongoUpdate(&vehicleFilterUpdateHelper{})

type vehicleFilterUpdateHelper struct {
	vehicleFiltersHelper
}

func (h *vehicleFilterUpdateHelper) ParseUpdateURLParams(r *http.Request) interface{} {
	req := &VehicleFilterParams{}

	params := httprouter.ParamsFromContext(r.Context())
	req.VIN = params.ByName("vin")
	req.CANID = params.ByName("id")

	return req
}

func (h *vehicleFilterUpdateHelper) ValidateFields(model interface{}) error {
	p, ok := model.(*VehicleFilterParams)
	if !ok {
		return nil
	}

	if p.VIN == "" || p.CANID == "" {
		return ErrInvalidURLParams
	}
	return nil
}

func (h *vehicleFilterUpdateHelper) ParseRequestBody(r *http.Request, model interface{}) error {
	if err := httphandlers.ParseRequest(r, model); err != nil {
		return errors.WithMessage(err, "failed to parse request body")
	}
	p := model.(*common.CANFilter)

	if p.EdgeMask == nil && p.Interval == nil {
		return &validator.FieldError{
			ErrorMsg: "At least one of edge_mask or interval is required",
		}
	}

	if p.EdgeMask != nil && p.Interval != nil {
		if (*p.EdgeMask).String() == "" && *p.Interval == 0 ||
			(*p.EdgeMask).String() != "" && *p.Interval != 0 {
			return &validator.FieldError{
				ErrorMsg: "Only one of edge_mask or interval can be specified",
			}
		}
	}

	return nil
}

func (h *vehicleFilterUpdateHelper) QueryUpdate(filter interface{}, model interface{}) error {
	client, err := services.GetMongoClient()
	if err != nil {
		return err
	}

	f := filter.(*VehicleFilterParams)
	if err = client.GetVehicles().UpdateFilterForVehicle(f.VIN, f.CANID, model.(*common.CANFilter)); err != nil {
		return err
	}

	return ResetVehiclesConfigCache([]string{f.VIN})
}
