package main

import (
	"fmt"
	"strings"
	"time"
)

// Schedule is the one posted opening per week, in the server's local zone.
type Schedule struct {
	Day  time.Weekday
	Hour int
	Min  int
}

// parseOpens reads the -opens flag, for example "Fri 16:00" or "Monday 09:30".
func parseOpens(v string) (Schedule, error) {
	bad := fmt.Errorf("-opens %q is not a weekday and a 24-hour time, for example \"Fri 16:00\". Not started.", v)
	f := strings.Fields(v)
	if len(f) != 2 || len(f[0]) < 3 {
		return Schedule{}, bad
	}
	day := -1
	for d := time.Sunday; d <= time.Saturday; d++ {
		if strings.HasPrefix(strings.ToLower(d.String()), strings.ToLower(f[0])) {
			day = int(d)
		}
	}
	hm, err := time.Parse("15:04", f[1])
	if day < 0 || err != nil {
		return Schedule{}, bad
	}
	return Schedule{Day: time.Weekday(day), Hour: hm.Hour(), Min: hm.Minute()}, nil
}

// on returns the posted hour on the calendar day `days` after t's day.
// time.Date in t's zone, never +168h, so a DST change does not move the hour.
func (s Schedule) on(t time.Time, days int) time.Time {
	y, m, d := t.Date()
	return time.Date(y, m, d+days, s.Hour, s.Min, 0, 0, t.Location())
}

// next is the first opening after t. An opening at exactly t is already
// past: it is the first instant of the new week.
func (s Schedule) next(t time.Time) time.Time {
	ahead := (int(s.Day) - int(t.Weekday()) + 7) % 7
	if o := s.on(t, ahead); o.After(t) {
		return o
	}
	return s.on(t, ahead+7)
}

// prev is the last opening at or before t.
func (s Schedule) prev(t time.Time) time.Time {
	back := (int(t.Weekday()) - int(s.Day) + 7) % 7
	if o := s.on(t, -back); !o.After(t) {
		return o
	}
	return s.on(t, -back-7)
}

// atKey is the posted hour on the date a box file is keyed by.
func (s Schedule) atKey(key string, loc *time.Location) time.Time {
	d, _ := time.ParseInLocation("2006-01-02", key, loc)
	return s.on(d, 0)
}

// past reports whether a box key's opening is at or before t. A key left by
// an earlier -opens setting is placed by its date at the posted hour.
func (s Schedule) past(key string, t time.Time) bool {
	return !s.atKey(key, t.Location()).After(t)
}

// lastInstant is the latest moment a snapshot is due at or before t:
// the top of the hour or the opening, whichever is later.
func (s Schedule) lastInstant(t time.Time) time.Time {
	if h, o := hourFloor(t), s.prev(t); o.After(h) {
		return o
	}
	return hourFloor(t)
}

func (s Schedule) plate() string {
	return fmt.Sprintf("Opens %ss %02d:%02d", s.Day, s.Hour, s.Min)
}

func keyOf(t time.Time) string { return t.Format("2006-01-02") }

// hourFloor is the local top of the hour; subtracting the local minute keeps
// half-hour zones and DST days right, where Truncate(time.Hour) would not.
func hourFloor(t time.Time) time.Time {
	return t.Truncate(time.Minute).Add(-time.Duration(t.Minute()) * time.Minute)
}

// plural writes "1 note" or "9 notes"; every printed count uses it.
func plural(n int, one, many string) string {
	if n == 1 {
		return "1 " + one
	}
	return fmt.Sprintf("%d %s", n, many)
}

// spell writes a -window value for the conditions page: "24 hours", "2 minutes".
func spell(d time.Duration) string {
	var parts []string
	for _, u := range []struct {
		d         time.Duration
		one, many string
	}{{time.Hour, "hour", "hours"}, {time.Minute, "minute", "minutes"}, {time.Second, "second", "seconds"}} {
		if n := int(d / u.d); n > 0 {
			parts = append(parts, plural(n, u.one, u.many))
			d -= time.Duration(n) * u.d
		}
	}
	if len(parts) == 0 {
		return d.String()
	}
	return strings.Join(parts, " ")
}
