package webhook

import (
	"context"
	"io"
	"log"
	"net/http"
	"sync"
	"text/template"

	"git.luj0ga.de/franconian/matrix"
)

type Server struct {
	matrix	*matrix.Client
	tmpl	*template.Template
}

func NewServer(matrix *matrix.Client) *Server {
	return &Server{
		matrix:	matrix,
		tmpl:	template.Must(template.New("alert").Parse(messageTemplate)),
	}
}

func (s Server) ListenAndServe(address string, ctx context.Context, wg *sync.WaitGroup) error {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusNoContent)
	})
	http.HandleFunc("/webhook", s.handleWebhook)

	server := http.Server{
		Addr:	address,
	}

	go func() {
		wg.Add(1)
		defer wg.Done()

		<-ctx.Done()

		err := server.Shutdown(context.Background())
		if err != nil {
			log.Print(err)
		}
	}()

	log.Print("listening on ", address)

	err := server.ListenAndServe()
	if err != http.ErrServerClosed {
		return err
	}

	return nil
}

func writeStatus(w http.ResponseWriter, code int) {
	w.WriteHeader(code)
	io.WriteString(w, http.StatusText(code))
}
