// Command opens-fridays is a suggestion box on the local network. It shows
// only how many notes are inside, and opens once a week at a posted time.
package main

import (
	"bytes"
	"embed"
	"errors"
	"flag"
	"fmt"
	"html/template"
	"io"
	"log"
	"net"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
	_ "time/tzdata" // TZ=Europe/Berlin works on a machine without a zone database
)

//go:embed templates
var templateFS embed.FS

//go:embed static
var staticFS embed.FS

func main() {
	addr := flag.String("addr", ":8080", "listen address")
	dir := flag.String("data", "./data", "data directory")
	opens := flag.String("opens", "Fri 16:00", "the weekly opening: weekday and 24-hour time, local zone")
	window := flag.Duration("window", 24*time.Hour, "how long an opened box is shown")
	flag.Parse()
	if err := run(*addr, *dir, *opens, *window); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func run(addr, dir, opens string, window time.Duration) error {
	s, err := parseOpens(opens)
	if err != nil {
		return err
	}
	if window <= 0 {
		return errors.New("-window must be above zero. Not started.")
	}
	ln, err := net.Listen("tcp", addr)
	if err != nil {
		return fmt.Errorf("%v. Not started.", err)
	}
	b, err := openBox(dir, s, window, time.Now)
	if err != nil {
		ln.Close()
		return err
	}
	url := startURL(addr, ln.Addr().(*net.TCPAddr).Port, lanIP)
	fmt.Printf("%s  %s  %s\n", url, s.plate(), zoneName())
	b.start()
	srv := &http.Server{
		Handler:           routes(b, url),
		ErrorLog:          log.New(io.Discard, "", 0), // the default one writes client addresses
		ReadHeaderTimeout: 10 * time.Second,
	}
	return srv.Serve(ln)
}

// startURL is the address printed at start and on the door card. An
// unspecified host is replaced by the machine's own LAN address.
func startURL(addr string, port int, detect func() string) string {
	host, _, _ := net.SplitHostPort(addr)
	if ip := net.ParseIP(host); host == "" || ip != nil && ip.IsUnspecified() {
		host = detect()
	}
	return "http://" + net.JoinHostPort(host, strconv.Itoa(port))
}

// lanIP names the default-route interface. A UDP dial sends no packet.
func lanIP() string {
	if c, err := net.Dial("udp4", "192.0.2.1:9"); err == nil {
		ip := c.LocalAddr().(*net.UDPAddr).IP
		c.Close()
		if !ip.IsLoopback() && !ip.IsUnspecified() {
			return ip.String()
		}
	}
	addrs, _ := net.InterfaceAddrs()
	for _, a := range addrs {
		if n, ok := a.(*net.IPNet); ok && n.IP.To4() != nil && !n.IP.IsLoopback() {
			return n.IP.To4().String()
		}
	}
	return "localhost"
}

func zoneName() string {
	if n := time.Local.String(); n != "Local" {
		return n
	}
	if p, err := os.Readlink("/etc/localtime"); err == nil {
		if _, z, ok := strings.Cut(p, "zoneinfo/"); ok {
			return z
		}
	}
	return time.Now().Format("MST")
}

var pages = func() map[string]*template.Template {
	m := map[string]*template.Template{}
	for _, name := range []string{"front", "conditions", "message", "plate"} {
		files := []string{"templates/page.html", "templates/" + name + ".html"}
		if name == "front" {
			files = append(files, "templates/sheet.html")
		}
		m[name] = template.Must(template.ParseFS(templateFS, files...))
	}
	return m
}()

func render(w http.ResponseWriter, status int, name string, data any) {
	var buf bytes.Buffer
	if err := pages[name].ExecuteTemplate(&buf, "page", data); err != nil {
		http.Error(w, "The page could not be drawn.", http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.WriteHeader(status)
	w.Write(buf.Bytes())
}

// message is the shell for the received page and every error page. Form puts
// the form back with Text in it, exactly as typed.
type message struct {
	Line  string
	Error bool
	Form  bool
	Text  string
}

func routes(b *Box, url string) http.Handler {
	day := b.sched.Day.String()
	mux := http.NewServeMux()
	mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
		v, err := b.view()
		if err != nil {
			render(w, http.StatusInternalServerError, "message", message{Line: "The box could not be read.", Error: true})
			return
		}
		render(w, http.StatusOK, "front", v)
	})
	mux.HandleFunc("POST /put", func(w http.ResponseWriter, r *http.Request) {
		if r.Header.Get("Sec-Fetch-Site") == "cross-site" {
			render(w, http.StatusForbidden, "message", message{Line: "Notes are put in from this page only.", Error: true})
			return
		}
		r.Body = http.MaxBytesReader(w, r.Body, 8<<10)
		if err := r.ParseForm(); err != nil {
			var big *http.MaxBytesError
			if errors.As(err, &big) {
				render(w, http.StatusRequestEntityTooLarge, "message", message{Line: "That is 500 characters at most. The box has not been changed.", Error: true, Form: true})
				return
			}
			render(w, http.StatusBadRequest, "message", message{Line: "Nothing was written. Nothing was put in.", Error: true, Form: true})
			return
		}
		raw := r.PostForm.Get("note")
		switch err := b.add(raw); {
		case err == nil:
			http.Redirect(w, r, "/received", http.StatusSeeOther)
		case errors.Is(err, errEmpty):
			render(w, http.StatusBadRequest, "message", message{Line: "Nothing was written. Nothing was put in.", Error: true, Form: true})
		case errors.Is(err, errTooLong):
			render(w, http.StatusRequestEntityTooLarge, "message", message{Line: "That is 500 characters at most. The box has not been changed.", Error: true, Form: true, Text: raw})
		case errors.Is(err, errFull):
			render(w, http.StatusConflict, "message", message{Line: "The box is full. It will be empty again after it opens.", Error: true, Form: true, Text: raw})
		default:
			render(w, http.StatusInternalServerError, "message", message{Line: "The box could not be read. Nothing was put in.", Error: true, Form: true, Text: raw})
		}
	})
	mux.HandleFunc("GET /received", func(w http.ResponseWriter, r *http.Request) {
		render(w, http.StatusOK, "message", message{Line: "Received. It will keep until " + day + "."})
	})
	mux.HandleFunc("GET /conditions", func(w http.ResponseWriter, r *http.Request) {
		render(w, http.StatusOK, "conditions", struct{ Window string }{spell(b.window)})
	})
	mux.HandleFunc("GET /plate", func(w http.ResponseWriter, r *http.Request) {
		render(w, http.StatusOK, "plate", struct{ Plate, URL string }{b.sched.plate(), url})
	})
	mux.HandleFunc("GET /static/{name}", func(w http.ResponseWriter, r *http.Request) {
		data, err := staticFS.ReadFile("static/" + r.PathValue("name"))
		if err != nil {
			http.NotFound(w, r)
			return
		}
		// Zero modtime: no Last-Modified. No ETag is ever set.
		http.ServeContent(w, r, r.PathValue("name"), time.Time{}, bytes.NewReader(data))
	})
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Cache-Control", "no-store")
		mux.ServeHTTP(w, r)
	})
}
