package ws

import (
	"net/http"

	"git.paulbsd.com/paulbsd/dip/src/dip"
	"git.paulbsd.com/paulbsd/dip/src/templates"
	"github.com/labstack/echo/v4"
)

func (p *Page) GetContent(c echo.Context) (cached bool, err error) {
	var ip dip.IP
	cached, err = ip.GetIPInfo(c)
	p.IP = &ip

	return
}

// Process returns main webpage or a JSON
func (p *Page) Process(c echo.Context, querytype string) (err error) {
	cached, err := p.GetContent(c)
	c.Response().Header().Set("X-Cached", "false")
	if cached {
		c.Response().Header().Set("X-Cached", "true")
	}
	if querytype == "json" {
		return c.JSON(http.StatusOK, p.IP)
	}
	if accept, ok := c.Request().Header["Accept"]; ok {
		if accept[0] == "*/*" {
			return c.JSON(http.StatusOK, p.IP)
		}
	}
	return c.Render(http.StatusOK, "index.html", p)
}

// Page defines Web page
type Page struct {
	Title     string
	Templates *templates.Template
	IP        *dip.IP
}
