package main

import (
	"fmt"
	"net/http"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

type WebServer struct {
	tv_ip string
	Port  string
	Host  string
	At    string
}

func (w *WebServer) Init(tv, host, port string) {
	w.tv_ip = tv
	w.Host = host
	w.Port = port
	w.At = DebugInfo(w.tv_ip)
}

func (w *WebServer) homepage(c echo.Context) error {
	//return c.String(http.StatusOK, "Hello World!")
	/*file, err := os.ReadFile("templates/index.html")
	if err != nil {
		return err
	}*/

	//return c.HTMLBlob(http.StatusOK, file)
	data := make(map[string]interface{})
	data["at"] = w.At
	return c.Render(http.StatusOK, "index.html", data)
}

func (w *WebServer) tvcmd(c echo.Context) error {
	//w.At = DebugInfo(w.tv_ip)
	cmd := c.Param("cmd")
	switch cmd {
	case "power":
		PerformKey(w.tv_ip, "power")
	case "back":
		PerformKey(w.tv_ip, "back")
	case "home":
		PerformKey(w.tv_ip, "home")
	case "up":
		PerformKey(w.tv_ip, "up")
	case "left":
		PerformKey(w.tv_ip, "left")
	case "ok":
		PerformKey(w.tv_ip, "select")
	case "right":
		PerformKey(w.tv_ip, "right")
	case "down":
		PerformKey(w.tv_ip, "down")
	case "rewind":
		PerformKey(w.tv_ip, "rev")
	case "play-pause":
		PerformKey(w.tv_ip, "play")
	case "fast-forward":
		PerformKey(w.tv_ip, "fwd")
	case "star":
		PerformKey(w.tv_ip, "info")
	case "reload":
		PerformKey(w.tv_ip, "instantreplay")
	case "vol+":
		PerformKey(w.tv_ip, "volumeup")
	case "vol-":
		PerformKey(w.tv_ip, "volumedown")
	case "mute":
		PerformKey(w.tv_ip, "volumemute")
	case "display":
		w.At = DebugInfo(w.tv_ip)
		data := make(map[string]interface{})
		data["at"] = w.At
		return c.String(http.StatusOK, w.At)
	case "pluto":
		Post(fmt.Sprintf("http://%s:8060/launch/%d", w.tv_ip, 74519))
	case "pluto-cops":
		Post(fmt.Sprintf("http://%s:8060/launch/%d?contentId=367&mediaType=live", w.tv_ip, 74519))
	case "pluto-thefirst":
		Post(fmt.Sprintf("http://%s:8060/launch/%d?contentId=244&mediaType=live", w.tv_ip, 74519))
	case "pluto-mst3k":
		Post(fmt.Sprintf("http://%s:8060/launch/%d?contentId=488&mediaType=live", w.tv_ip, 74519))
	case "pluto-rifftrax":
		Post(fmt.Sprintf("http://%s:8060/launch/%d?contentId=489&mediaType=live", w.tv_ip, 74519))
	case "pluto-startrek":
		Post(fmt.Sprintf("http://%s:8060/launch/%d?contentId=150&mediaType=live", w.tv_ip, 74519))
	default:
		c.Echo().Logger.Printf("Got '%v'\r\n", cmd)
	}
	return c.Redirect(http.StatusOK, "/")
	//return c.Render(http.StatusOK, "index.html", data)
}

func main() {
	web := WebServer{}
	web.Init("192.168.254.75", "", "8000")
	e := echo.New()
	e.Use(middleware.Logger())
	e.Use(middleware.Static("static"))
	e.Renderer = NewRenderer("./templates/*.html", true)
	e.GET("/", web.homepage)
	e.GET("/tv/:cmd", web.tvcmd)
	e.Logger.Fatal(e.Start(fmt.Sprintf("%s:%s", web.Host, web.Port)))
}
