package main

import (
	"context"
	"fmt"
	"io"
  "net"

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

)

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

/* Grid square size is in decimal degrees.  0.1 degrees produces a
  square of approximately 11km across (123 square kilometers), or
  about 12 million unique locations on the Earth's surface
  (albeit most of them will be ocean)
*/

const ChunkSize = 0.1

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		
    if ChunkSize > 0 {
    // Get client IP address.
      clientIP := net.ParseIP(r.RemoteAddr)
    // Lookup geo metada associated with the client IP address.
      geo, err := geo.Lookup(clientIP)
      if err != nil {
        w.WriteHeader(fsthttp.StatusInternalServerError)
        fmt.Fprintln(w, err.Error())
        return
      }
    // Round to 1 decimal point
      GridID := fmt.Sprintf("%.1f,%.1f", geo.Latitude, geo.Longitude)

      fmt.Println("Grid ID:", GridID, "Nearest city:", geo.City)
  
      r.Header.Add("geo-grid-id", GridID)
    }
    
    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)
	})
}