package mainwindow

import (
	"fmt"
	"lab.zaar.be/thefish/alchemyst-go/engine/gamestate"
	"lab.zaar.be/thefish/alchemyst-go/engine/types"
)

type ViewPort struct {
	types.Rect
	CameraCoords types.Coords
}

func NewViewPort(x, y, w, h int) *ViewPort {
	vp := ViewPort{
		Rect:  types.Rect{X: x, Y: y, W: w, H: h},
	}
	return &vp
}

func (vp *ViewPort) Move(state *gamestate.GameState, newCoords types.Coords) {

	x := newCoords.X - vp.Rect.W/2
	y := newCoords.Y - vp.Rect.H/2

	if x < 0 {
		x = 0
	}
	if y < 0 {
		y = 0
	}
	if x > state.Level.W - vp.W - 1 {
		x = state.Level.W - vp.W
	}
	if y > state.Level.H-vp.H - 1 {
		y = state.Level.H - vp.H
	}
	if x != vp.CameraCoords.X || y != vp.CameraCoords.Y {
		state.FovRecompute <- struct{}{}
	}
	vp.CameraCoords.X = x
	vp.CameraCoords.Y = y

}

func (vp *ViewPort) ToVPCoords(c types.Coords) (newCoords types.Coords, err error) {
	//coords on map to coords on vp
	x, y := c.X-vp.CameraCoords.X, c.Y-vp.CameraCoords.Y
	if x < 0 || y < 0 || x > vp.W || y > vp.H {
		return types.Coords{X: -1, Y: -1}, fmt.Errorf("Not in viewport: {%d, %d}", x, y)
	}
	return types.Coords{X: x, Y: y}, nil
}

