package app

import (
	"fmt"

	"code.tnxs.net/taxnexus/lib/api/geo/geo_client/place"
	"code.tnxs.net/taxnexus/lib/api/geo/geo_models"
)

// GetPlaceNameByGeocode is first class retrieval function
func GetPlaceNameByGeocode(key string, principal *User) string {
	if key == "" || len(key) == 7 {
		return ""
	}
	p, ok := placeCache.get(key)
	if ok {
		return p.Name
	}
	thePlace, err := GetPlaceByGeocode(key, principal)
	if err != nil {
		return ""
	}
	return thePlace.Name
}

// GetPlaceHasDistrictTaxesByGeocode is first class retrieval function
func GetPlaceHasDistrictTaxesByGeocode(key string, principal *User) bool {
	if key == "" || len(key) == 7 {
		return false
	}
	p, ok := placeCache.get(key)
	if ok {
		return p.HasDistrictTaxes
	}
	thePlace, err := GetPlaceByGeocode(key, principal)
	if err != nil {
		return false
	}
	return thePlace.HasDistrictTaxes
}

// GetPlaceByGeocode is first class retrieval function
func GetPlaceByGeocode(recordID string, principal *User) (geo_models.Place, error) {
	sugar.Debug("plex.getPlaceByGeocode: 📥")
	if recordID == "" {
		return geo_models.Place{}, fmt.Errorf("plex.getPlaceByID: 💣 ⛔ key is blank")
	}
	obj, ok := placeCache.get(recordID)
	if ok {
		sugar.Debug("plex.getPlaceByGeocode: 👍 🎯 📤")
		return *obj, nil
	}
	geoParams := place.NewGetPlacesParamsWithTimeout(getTimeout)
	geoParams.Geocode = &recordID
	response, err := geoClient.Place.GetPlaces(geoParams, principal.Auth)
	if err != nil {
		return geo_models.Place{}, err
	}
	var newObj *geo_models.Place
	for _, itm := range response.Payload.Data { // single iteration execution
		newObj = itm
	}
	placeCache.put(recordID, newObj)
	sugar.Debug("plex.getPlaceByGeocode: 👍 🆕 📤")
	return *newObj, nil
}
