package placesroute

import (
	"sync"

	"bitbucket.org/nemt/nemt-portal-api/application/applicationservice"
	"bitbucket.org/nemt/nemt-portal-api/infra/config"
	"bitbucket.org/nemt/nemt-portal-api/server/router/routeutils"
	"github.com/labstack/echo"
	"golang.org/x/net/context"
	"googlemaps.github.io/maps"
)

var (
	instance *controller
	once     sync.Once
)

type controller struct {
	cfg  *config.Config
	svc  *applicationservice.Service
	maps *maps.Client
}

func controllerInstance(cfg *config.Config, svc *applicationservice.Service) *controller {
	once.Do(func() {
		c, _ := maps.NewClient(maps.WithClientIDAndSignature("gme-bluecrossandblue1", "msqgD-jdqCyR0M_1u5C1HION5iI="))
		instance = &controller{
			cfg:  cfg,
			svc:  svc,
			maps: c,
		}
	})

	return instance
}

func (c *controller) handle(ctx echo.Context) error {
	name, err := routeutils.GetAndValidateStringQueryParam(ctx, "name", "name is mandatory")
	if err != nil {
		return err
	}

	req := maps.PlaceAutocompleteRequest{
		Input:    name,
		Language: "en",
	}

	resp, err := c.maps.PlaceAutocomplete(context.Background(), &req)
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	return routeutils.ResponseAPIOK(ctx, resp)
}
