package ws

import (
	"encoding/json"
	"log"

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

// HandleWSRR handle req rep flows
func HandleWSRR(c echo.Context, cfg *config.Config) 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 {
			welcomeAgents(ws, welcome, "rr")
		}

		var lastip string
		for {
			var apievent = models.APIEvent{}
			var event = models.Event{}

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

			err = json.Unmarshal(msg, &apievent)
			if err != nil {
				log.Println(err)
			}

			if lastip != "" && apievent.IPData.IP == lastip {
				continue
			}

			switch apievent.MsgType {
			case "bootstrap":
				log.Printf("bootstrap: %s\n", apievent.Hostname)
				for index, value := range listeners {
					if index != apievent.Hostname && value.ConnectionPS != nil {
						err = websocket.Message.Send(value.ConnectionPS, msg)
						if err != nil {
							log.Println(err)
							gcConnOnError(ws)
						}
					}
				}
			case "add":
				session := cfg.Db.NewSession()
				event.APIParse(session, apievent)
				session.Close()

				err := event.Insert(cfg)
				if err != nil {
					log.Println(err)
				}

				for _, value := range listeners {
					if value.ConnectionPS != nil {
						err = websocket.Message.Send(value.ConnectionPS, msg)
						if err != nil {
							log.Println(err)
							gcConnOnError(ws)
						}
					}
				}
				log.Printf("ws: Inserted event")
			case "init":
				for _, value := range listeners {
					if value.ConnectionPS != nil {
						err = websocket.Message.Send(value.ConnectionPS, msg)
						if err != nil {
							log.Println(err)
							gcConnOnError(ws)
						}
					}
				}
			default:
			}

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

			/*
				WebSocketChannel <- apievent

				err = websocket.Message.Send(ws, "OK")
				if err != nil {
					//gcConn(ws, "rr")
					log.Println(listeners)
					return
				}
			*/

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