package server

import (
	"errors"

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

func (g *game) near(x, y int) bool {
	return world.Distance(g.state.Party.X, g.state.Party.Y, x, y) <= 1
}

func (g *game) interact(id string) error {
	g.begin()
	if p := g.poi(id); p != nil {
		if !g.near(p.X, p.Y) {
			return errors.New("too far away")
		}
		if !p.Cleared {
			if !g.bossGate(p) {
				return errors.New("the way is barred: finish the other main steps first")
			}
			g.state.Party.X, g.state.Party.Y = p.X, p.Y
			g.fight(p.ID, p.X, p.Y, func() { p.Cleared = true })
		}
		return nil
	}
	if b := g.band(id); b != nil && !b.Cleared {
		if !g.near(b.X, b.Y) {
			return errors.New("too far away")
		}
		g.state.Party.X, g.state.Party.Y = b.X, b.Y
		g.fight(b.ID, b.X, b.Y, func() { b.Cleared = true })
		return nil
	}
	for i := range g.state.Map.Loot {
		l := &g.state.Map.Loot[i]
		if l.ID != id {
			continue
		}
		if l.Collected {
			return errors.New("already collected")
		}
		if !g.near(l.X, l.Y) {
			return errors.New("too far away")
		}
		l.Collected = true
		g.take(l.Item)
		g.advance()
		return nil
	}
	for _, s := range g.state.Map.Spawns {
		if s.ID == id {
			if !g.near(s.X, s.Y) {
				return errors.New("too far away")
			}
			return nil
		}
	}
	return errors.New("unknown id")
}

func (g *game) unit(id string) *model.Unit {
	for i := range g.state.Party.Units {
		if g.state.Party.Units[i].ID == id {
			return &g.state.Party.Units[i]
		}
	}
	return nil
}
