package web

import (
	"log"
	"net"
	"net/http"

	"github.com/Jaculabilis/intake/core"
)

type Env struct {
	db core.DB
}

func logged(handler http.HandlerFunc) http.HandlerFunc {
	return func(writer http.ResponseWriter, req *http.Request) {
		log.Printf("%s %s", req.Method, req.URL.Path)
		handler(writer, req)
	}
}

func handleFunc(pattern string, handler http.HandlerFunc) {
	http.HandleFunc(pattern, logged(handler))
}

func RunServer(db core.DB, addr string, port string) {
	env := &Env{db}
	bind := net.JoinHostPort(addr, port)

	handleFunc("GET    /", env.getRoot)
	handleFunc("GET    /style.css", env.getStyle)
	handleFunc("GET    /htmx.org@2.0.4.js", env.getScript)
	handleFunc("GET    /source/{source}", env.getSource)
	handleFunc("GET    /item/{source}/{id}", env.getItem)
	handleFunc("DELETE /item/{source}/{id}", env.deleteItem)
	handleFunc("POST   /item/{source}/{id}/action/{action}", env.doAction)
	handleFunc("POST   /mass-deactivate", env.massDeactivate)

	log.Fatal(http.ListenAndServe(bind, nil))
}