package main

import (
	"context"
	"fmt"
	"io"
	"math"
	"net"
	"strconv"

	"github.com/fastly/compute-sdk-go/fsthttp"
	"github.com/fastly/compute-sdk-go/geo"
)

// BackendName is the name of our service backend.
const BackendName = "origin_0"

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		// Do a geolocation lookup for this IP address
		client_geo, err := geo.Lookup(net.ParseIP(r.RemoteAddr))
		if err != nil {
			fmt.Print(err)
			w.WriteHeader(fsthttp.StatusInternalServerError)
			fmt.Fprint(w, "GEO Lookup Error: ", err)
			return
		}

		// Grab the offset from the geolocation data
		offset := client_geo.UTCOffset
		r.Header.Add("tz-offset-iso8601", strconv.Itoa(offset))

		// Round to a whole hour
		tz_hour := int(math.Round(float64(offset) / 100))
		r.Header.Add("tz-hour", strconv.Itoa(tz_hour))

		// Parse the time offset into a decimal number of hours
		tz_offset_hours := int(float64(offset%100)/60.0 + math.Round(float64(offset)/100.0))
		r.Header.Add("tz-offset-hours", strconv.Itoa(tz_offset_hours))

		// Round to nearest even hour
		tz_evenhour := int(math.Round(float64(offset)/100/2) * 2)
		r.Header.Add("tz-evenhour", strconv.Itoa(tz_evenhour))

		// Send the request to the origin with the additional headers
		resp, err := r.Send(ctx, BackendName)
		if err != nil {
			w.WriteHeader(fsthttp.StatusBadGateway)
			fmt.Fprintln(w, err.Error())
			return
		}

		w.Header().Reset(resp.Header)
		w.WriteHeader(resp.StatusCode)
		io.Copy(w, resp.Body)
	})
}