package main

import (
	"embed"
	"encoding/json"
	"fmt"
	"html/template"
	"math"
	"mime"
	"net/http"
	"path"
	"path/filepath"
	"sort"
	"strings"
	"time"
)

//go:embed web
var web embed.FS

var pages = template.Must(template.ParseFS(web, "web/index.html", "web/listings.html"))

type row struct {
	Frame                      int64
	Start, Title, Length, Note string
}

type dayView struct {
	Date, Heading string
	Rows          []row
	Open          *row // the slot on air: its start, never its title or length
	Empty         bool // the log has no rows: "No programme."
	Refused       []refusalView
}

type refusalView struct{ Name, Reason string }

func clock(t time.Time) string { return t.Format("15:04:05") }

func length(frames int64) string {
	sec := (frames + rate/2) / rate
	return fmt.Sprintf("%d:%02d", sec/60, sec%60)
}

// view lays out one day block: the slots ended by frame rel (the last `last` of
// them when last > 0), then, when open, the slot on air with no title and no length.
// Provenance notes belong to the printed record only.
func (s *station) view(l *dayLog, rel int64, open, provenance bool, last int) dayView {
	v := dayView{Date: l.date, Heading: l.start.Format("Monday 2 January 2006"), Empty: len(l.slots) == 0}
	gone := s.withdrawn(l.date)
	i, from := l.at(rel), 0
	if last > 0 {
		from = max(0, i-last)
	}
	for _, sl := range l.slots[from:i] {
		r := row{Frame: sl.start, Start: clock(l.start.Add(time.Duration(sl.start/rate) * time.Second).In(s.loc)), Title: title(sl.name), Length: length(sl.frames)}
		var notes []string
		switch {
		case gone[sl.start]:
			notes = append(notes, "Withdrawn. Silence, "+length(sl.frames)+".")
		case sl.frames < sl.fileFrames:
			notes = append(notes, "Ended by the clock.")
		}
		if provenance && !gone[sl.start] && sl.software != "" {
			notes = append(notes, "Transferred via "+sl.software+".")
		}
		r.Note = strings.Join(notes, " ")
		v.Rows = append(v.Rows, r)
	}
	if open && i < len(l.slots) && l.slots[i].start <= rel {
		sl := l.slots[i]
		v.Open = &row{Frame: sl.start, Start: clock(l.start.Add(time.Duration(sl.start/rate) * time.Second).In(s.loc))}
	}
	for _, r := range l.refused {
		v.Refused = append(v.Refused, refusalView{r.name, r.reason})
	}
	return v
}

// today returns today's log and the frame of the day now.
func (s *station) today() (*dayLog, int64, time.Time, error) {
	now := s.now()
	l, err := s.day(dayStart(now, s.loc))
	if err != nil {
		return nil, 0, now, err
	}
	return l, absFrame(now) - l.startA(), now, nil
}

type pageData struct {
	Clock, Zone string
	Now         int64 // epoch ms
	Offset      int   // seconds east of UTC
	Today       dayView
	Days        []dayView
}

func (s *station) handleIndex(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		notFound(w)
		return
	}
	l, rel, now, err := s.today()
	if err != nil {
		http.Error(w, "No programme.", http.StatusServiceUnavailable)
		return
	}
	_, off := now.In(s.loc).Zone()
	s.page(w, "index.html", pageData{Clock: clock(now.In(s.loc)), Zone: s.zone, Now: now.UnixMilli(), Offset: off, Today: s.view(l, rel, true, false, 5)})
}

func (s *station) handleListings(w http.ResponseWriter, r *http.Request) {
	l, rel, now, err := s.today()
	if err != nil {
		http.Error(w, "No programme.", http.StatusServiceUnavailable)
		return
	}
	d := pageData{Clock: clock(now.In(s.loc)), Zone: s.zone}
	names, _ := filepath.Glob(filepath.Join(s.dir, ".continuity", "????-??-??.tsv"))
	sort.Sort(sort.Reverse(sort.StringSlice(names)))
	for _, p := range names {
		date := strings.TrimSuffix(filepath.Base(p), ".tsv")
		start, err := time.ParseInLocation("2006-01-02", date, s.loc)
		if err != nil || date > l.date || len(d.Days) == 7 { // a later day is never printed
			continue
		}
		if date == l.date {
			d.Days = append(d.Days, s.view(l, rel, true, true, 0))
		} else if past, err := readLog(p, start); err == nil {
			d.Days = append(d.Days, s.view(past, math.MaxInt64, false, true, 0))
		}
	}
	s.page(w, "listings.html", d)
}

type jsonRow struct {
	Start  string `json:"start"`
	Frame  int64  `json:"frame"`
	Title  string `json:"title"`
	Length string `json:"length"`
	Note   string `json:"note"`
}

type jsonOpen struct {
	Start string `json:"start"`
	Frame int64  `json:"frame"`
}

func (s *station) handlePreviously(w http.ResponseWriter, r *http.Request) {
	l, rel, now, err := s.today()
	if err != nil {
		http.Error(w, "No programme.", http.StatusServiceUnavailable)
		return
	}
	v := s.view(l, rel, true, false, 5)
	_, off := now.In(s.loc).Zone()
	out := struct {
		Now        int64     `json:"now"`
		Offset     int       `json:"offset"`
		Day        string    `json:"day"`
		Previously []jsonRow `json:"previously"`
		Open       *jsonOpen `json:"open"`
	}{Now: now.UnixMilli(), Offset: off, Day: v.Heading, Previously: []jsonRow{}}
	for i := len(v.Rows) - 1; i >= 0; i-- { // newest first
		r := v.Rows[i]
		out.Previously = append(out.Previously, jsonRow{r.Start, r.Frame, r.Title, r.Length, r.Note})
	}
	if v.Open != nil {
		out.Open = &jsonOpen{v.Open.Start, v.Open.Frame}
	}
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Cache-Control", "no-store")
	json.NewEncoder(w).Encode(out)
}

func (s *station) page(w http.ResponseWriter, name string, d pageData) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.Header().Set("Cache-Control", "no-store")
	// ponytail: the templates are covered by the tests, so the only error left here is
	// a listener who closed the page early, which is not an event for the console.
	pages.ExecuteTemplate(w, name, d)
}

func notFound(w http.ResponseWriter) {
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.WriteHeader(http.StatusNotFound)
	fmt.Fprint(w, "No such programme.")
}

func (s *station) mux() *http.ServeMux {
	m := http.NewServeMux()
	m.HandleFunc("/", s.handleIndex)
	m.HandleFunc("/listings", s.handleListings)
	m.HandleFunc("/previously.json", s.handlePreviously)
	m.HandleFunc("/stream.wav", s.handleStream)
	for _, n := range []string{"style.css", "tokens.css", "tune.js", "wordmark.svg", "favicon.svg"} {
		b, _ := web.ReadFile("web/" + n)
		ct := mime.TypeByExtension(path.Ext(n))
		m.HandleFunc("/"+n, func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("Content-Type", ct)
			w.Write(b)
		})
	}
	return m
}
