package controllers

import (
	"github.com/astaxie/beego"
	"github.com/gorilla/websocket"

	"git.kingpenguin.tk/chteufleur/datahouse.git/models/variables"
	"git.kingpenguin.tk/chteufleur/datahouse.git/watchlog"

	"net/http"
)

type WebSocketController struct {
	beego.Controller
}

func (c *WebSocketController) Prepare() {
	sess := c.GetSession(variables.SessionName)
	if sess == nil {
		c.Redirect(variables.LoginRouteNoRegex+variables.ViewLogRoute, 302)
	} else {
		c.Data["IsAuthentificated"] = true
	}

	c.Data["IsLog"] = true
	c.Data["version"] = variables.Version
}

// Get method handles GET requests for WebSocketController.
func (c *WebSocketController) Get() {
	c.Data["hostWS"] = "ws://" + c.Ctx.Request.Host + variables.WebSocketLogRoute
	c.TplName = "watchlog.tpl"
}

// Join method handles WebSocket requests for WebSocketController.
func (this *WebSocketController) Join() {
	// Upgrade from http request to WebSocket.
	ws, err := websocket.Upgrade(this.Ctx.ResponseWriter, this.Ctx.Request, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(this.Ctx.ResponseWriter, "Not a websocket handshake", 400)
		return
	} else if err != nil {
		beego.Error("Cannot setup WebSocket connection:", err)
		return
	}

	watchlog.ListWebSocket.PushFront(ws)

	// Message receive loop.
	for {
		_, _, err := ws.ReadMessage()
		if err != nil {
			return
		}
	}
	this.Ctx.Output.Body([]byte(""))
}
