package ws

import (
	"encoding/json"
	"log"
	"time"

	"git.paulbsd.com/paulbsd/ipbl/src/config"
	"github.com/labstack/echo/v4"
	"golang.org/x/net/websocket"
)

// HandleWSPS handle pub sub flows
func HandleWSPS(c echo.Context, cfg *config.Config) (err error) {
	websocket.Handler(func(ws *websocket.Conn) {
		defer ws.Close()

		var welcome = wsWelcome{}

		var msg []byte
		err := websocket.Message.Receive(ws, &msg)
		if err != nil {
			log.Println(err)
		}

		err = json.Unmarshal(msg, &welcome)
		if err != nil {
			log.Println(err)
		} else {
			welcomeAgents(ws, welcome, "ps")
		}

		err = websocket.Message.Receive(ws, "OK")
		if err != nil {
			log.Println(err)
		}

		for {
			time.Sleep(50 * time.Millisecond)
		}

		/*for {
			var apievent, ok = <-WebSocketChannel
			if ok {
				log.Println(apievent, ok)
				data, err := json.Marshal(apievent)
				if err != nil {
					log.Println(err)
				}
				err = websocket.Message.Send(ws, data)
				if err != nil {
					//gcConn(ws, "ps")
					log.Println(LISTENERS)
					return
				}
			}
		}*/

	}).ServeHTTP(c.Response(), c.Request())
	return nil
}
