package main

import (
	"bytes"
	"image/png"
	"net/http"
	"os"

	"github.com/Xe/ln"
	"github.com/Xe/ln/ex"
	"github.com/Xe/uuid"
	"github.com/golang/groupcache"
	qidenticon "github.com/jakobvarmose/go-qidenticon"
	chi "gopkg.in/chi.v3"
)

const (
	avatarWidth = 512
	fiftyMegs   = 1024 * 1024 * 50
)

func makeQidenticon(ctx groupcache.Context, key string, dest groupcache.Sink) error {
	img := qidenticon.Render(qidenticon.Code(key), avatarWidth, qidenticon.DefaultSettings())
	buf := bytes.NewBuffer(nil)

	err := png.Encode(buf, img)
	if err != nil {
		return err
	}

	dest.SetBytes(buf.Bytes())
	return nil
}

func main() {
	g := groupcache.NewGroup("identicons", fiftyMegs, groupcache.GetterFunc(makeQidenticon))

	r := chi.NewRouter()
	r.Use(ex.HTTPLog)

	r.Get("/", func(w http.ResponseWriter, r *http.Request) {
		http.Redirect(w, r, "/"+uuid.New(), http.StatusTemporaryRedirect)
	})

	r.Get("/{hash}", func(w http.ResponseWriter, r *http.Request) {
		var bs []byte
		sink := groupcache.AllocatingByteSliceSink(&bs)
		hash := chi.URLParam(r, "hash")

		err := g.Get(r.Context(), hash, sink)
		if err != nil {
			ln.Error(r.Context(), err, ln.Action("can't get hash"), ln.F{"hash": hash})
			http.Error(w, "internal server error, please contact the admin", http.StatusInternalServerError)
			return
		}

		w.Header().Add("Content-Type", "image/png")
		w.Write(bs)
	})
	http.ListenAndServe(":"+os.Getenv("PORT"), r)
}
