package server

import (
	"errors"

	"tinyadventure/internal/model"
	"tinyadventure/internal/world"
)

const (
	dayLength   = 140
	nightLength = 40
	fightTime   = 8
	campPC      = 50
)

func newClock() model.Clock {
	return model.Clock{Day: 1, DayLength: dayLength, NightLength: nightLength}
}

func (g *game) pass(t int) {
	c := &g.state.Clock
	dusk := c.Night()
	c.Time += t
	if c.Time >= c.DayLength+c.NightLength {
		c.Day++
		c.Time = 0
		g.note("Dawn breaks without rest")
	} else if !dusk && c.Night() {
		g.note("Night falls. Make camp if you carry supplies, or press on in the dark")
	}
}

func (g *game) rest() error {
	c := &g.state.Clock
	if g.blockerNear() {
		return errors.New("enemies are too close to make camp")
	}
	if g.state.Party.Supplies == 0 {
		return errors.New("no camp supplies left: buy them at a spawn or a place you have cleared")
	}
	g.begin()
	g.state.Party.Supplies--
	g.mend(campPC, true)
	g.state.Summary.Camps++
	c.Day++
	c.Time = 0
	return nil
}

func (g *game) blockerNear() bool {
	px, py := g.state.Party.X, g.state.Party.Y
	for _, p := range g.state.Map.POIs {
		if !p.Cleared && world.Distance(p.X, p.Y, px, py) <= 1 {
			return true
		}
	}
	for _, b := range g.state.Map.Bands {
		if !b.Cleared && world.Distance(b.X, b.Y, px, py) <= 1 {
			return true
		}
	}
	return false
}
