package handlers

import (
	"net/http"

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

	"otaupdate/controllers"
	"otaupdate/services"

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

	"github.com/julienschmidt/httprouter"
)

// HandleVehicleFilterAdd godoc
// @Summary Add CAN filter for vehicle
// @Description Add CAN filter for vehicle
// @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 config body VehicleFilterRequest true "CAN filter"
// @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 [post]
func HandleVehicleFilterAdd(w http.ResponseWriter, r *http.Request) {
	vehicleFilterAdd.Handle(w, r)
}

var vehicleFilterAdd = controllers.NewMongoUpdate(&vehicleFilterAddHelper{})

type vehicleFilterAddHelper struct {
	vehicleFiltersHelper
}

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

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

	return req
}

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

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

func (h *vehicleFilterAddHelper) ParseRequestBody(r *http.Request, model interface{}) error {
	if err := httphandlers.ParseRequest(r, model); err != nil {
		return errors.WithMessagef(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 *vehicleFilterAddHelper) QueryUpdate(filter interface{}, model interface{}) error {
	client, err := services.GetMongoClient()
	if err != nil {
		return err
	}

	err = client.GetVehicles().AddFilterToVehicle(filter.(*VehicleFilterParams).VIN, model.(*common.CANFilter))
	if err != nil {
		return err
	}

	return ResetVehiclesConfigCache([]string{filter.(*VehicleFilterParams).VIN})
}

func ResetVehiclesConfigCache(vins []string) error {
	r := services.RedisClientPool().GetFromPool()
	defer r.Close()

	if err := cache.RemoveCacheConfigForVehicles(r, vins); err != nil {
		if len(vins) == 1 {
			logger.Warn().Msgf("Failed to remove cache for %d vehicle", len(vins))
		} else {
			logger.Warn().Msgf("Failed to remove cache for %d vehicles", len(vins))
		}
	}

	return nil
}

type VehicleFilterRequest struct {
	CANID    string            `json:"can_id"`
	Interval *int              `json:"interval"`
	EdgeMask *common.BinaryHex `json:"edge_mask"`
}

type vehicleFiltersHelper struct{}

func (h *vehicleFiltersHelper) NewModel() interface{} {
	return &common.CANFilter{}
}

func (h *vehicleFiltersHelper) HasPK(model interface{}) bool {
	return model.(*common.CANFilter).CANID != ""
}

func (h *vehicleFiltersHelper) ValidatePK(model interface{}) error {
	result := model.(*VehicleFilterParams)

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

	return nil
}

type VehicleFilterParams struct {
	VIN string `json:"vin" validate:"required,vin"`
	common.CANFilter
}
