package ws

import (
	"time"

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

var webSocketChannel = make(chan models.APIEvent, 100)
var webSocketChannelDone = make(chan bool)

var listeners map[string]*connectionInfo

func Init(cfg *config.Config) {
	listeners = make(map[string]*connectionInfo)
}

func welcomeAgents(ws *websocket.Conn, welcome wsWelcome, t string) {
	connectinfo, ok := listeners[welcome.Hostname]

	if !ok {
		switch t {
		case "ps":
			connectinfo := connectionInfo{
				ConnectionPS: ws,
				InitDate:     time.Now(),
			}
			listeners[welcome.Hostname] = &connectinfo
		case "rr":
			connectinfo := connectionInfo{
				ConnectionRR: ws,
				InitDate:     time.Now(),
			}
			listeners[welcome.Hostname] = &connectinfo
		}
	} else {
		switch t {
		case "ps":
			connectinfo.ConnectionPS = ws
		case "rr":
			connectinfo.ConnectionRR = ws
		}
	}
}

func gcConnOnError(ws *websocket.Conn) (err error) {
	for index, value := range listeners {
		if value.ConnectionPS == ws {
			value.ConnectionPS.Close()
			delete(listeners, index)
		} else if value.ConnectionRR == ws {
			value.ConnectionRR.Close()
			delete(listeners, index)
		}
	}
	return err
}

type connectionInfo struct {
	ConnectionPS *websocket.Conn
	ConnectionRR *websocket.Conn
	InitDate     time.Time
}

// WSWelcome
type wsWelcome struct {
	Hostname string
}
