package comm

import (
	"fmt"
	"net"
)

type QuitCtx map[string]interface{}

type QuiteHandle func(ctx QuitCtx) bool

var _quitCtx = make(map[string]interface{})
var _listeners = []QuiteHandle{}

func InitQuitCtx(ctx QuitCtx) {
	_quitCtx = ctx
}

func PushQuitHandle(handle QuiteHandle) {
	_listeners = append(_listeners, handle)
}

func onQuite() {
	t := len(_listeners)
	for i, h := range _listeners {
		isBreak := h(_quitCtx)
		fmt.Println("[quit] ", i, "/", t, "breaking next =>", isBreak)
		if isBreak {
			break
		}
	}
}

var QuitChan = make(chan int)

func InitQuitSocket(port int) error {
	if port <= 0 {
		p, e := GetFreePort()
		if e != nil {
			return e
		}
		port = p
	}

	ln, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
	if err != nil {
		fmt.Println("listen tcp err", err)
		return err
	}
	fmt.Println("quitsokect=>", port)

	go func() {
		// defer ln.Close()
		conn, err := ln.Accept()
		if err != nil {
			fmt.Println("Accept error=>", err)
			ln.Close()
			return
		}
		defer conn.Close() //接收
		onQuite()
		message := "pong"
		_, err = conn.Write([]byte(message))
		if err != nil {
			fmt.Println("Error sending message:", err)
		}
		QuitChan <- 1
	}()
	return nil
}
