package handler

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/paulmach/orb/geojson"
	"net/http"
)

func (handler *SolidarityServiceHandler) CalculateDurationBetweenFeatures(feature1, feature2 *geojson.Feature) (int64, error) {
	coords1 := feature1.Point()
	coords2 := feature2.Point()
	routing_base_url := handler.Config.GetString("routing.valhalla.base_url")
	url := fmt.Sprintf("%sroute?json=%s", routing_base_url, createJSONROUTERequest(coords1.X(), coords1.Y(), coords2.X(), coords2.Y()))
	response, err := http.Get(url)
	if err != nil {
		return 0, errors.New("routing service error")
	}
	var result map[string]interface{}
	decoder := json.NewDecoder(response.Body)
	if err := decoder.Decode(&result); err != nil {
		return 0, errors.New("routing response decoding error")
	}
	trip, ok := result["trip"].(map[string]interface{})
	if !ok {
		return 0, errors.New("routing response decoding error")
	}
	summary, ok := trip["summary"].(map[string]interface{})
	if !ok {
		return 0, errors.New("routing response decoding error")
	}
	duration, ok := summary["time"].(float64)
	if !ok {
		return 0, errors.New("routing response decoding error")
	}

	return int64(duration), nil
}

func createJSONROUTERequest(lat1, lon1, lat2, lon2 float64) string {
	request := map[string]interface{}{
		"locations": []map[string]float64{
			{"lat": lat1, "lon": lon1},
			{"lat": lat2, "lon": lon2},
		},
		"costing": "auto",
	}

	jsonRequest, _ := json.Marshal(request)
	return string(jsonRequest)
}
