package ws

import (
	"net/http"
	"strings"

	"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) (err error) {
	var ip dip.IP
	err = ip.GetIPInfo(c)
	p.IP = &ip

	return
}

// Index returns main webpage
func (p *Page) Index(c echo.Context) (err error) {
	p.GetContent(c)
	if strings.Contains(c.Request().Header.Get(echo.HeaderAccept), echo.MIMETextHTML) {
		return c.Render(http.StatusOK, "index.html", p)
	}
	return c.JSONPretty(http.StatusOK, p.IP, "  ")
}

func (p *Page) JSON(c echo.Context) (err error) {
	p.GetContent(c)
	return c.JSONPretty(http.StatusOK, p.IP, "  ")
}

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