package main

/// 2019-09-01 仅监控自身节点，是否被通知退出，处理退出指令.(如果发出退出指令，不能撤销，不能搞的无谓的复杂)

import (
	"encoding/json"

	"../conf"
	"../gameapi"
	"../log"
	"../nt"
	pb "../protos"
	"../zkeeper"
	"github.com/samuel/go-zookeeper/zk"
	"go.uber.org/zap"
)

func on_notify_node_event(c *zkeeper.ZkClient, path string, ev zk.EventType) {
	log.Info("zk node changed", zap.String("name", path), zap.Int32("event", int32(ev)))
	if ev == zk.EventNodeDataChanged {
		switch path {
		case nt.ZkP.Wallet:
			gameapi.InitGameAPIConf()
			return
		case nt.ZkP.Games:
			// 广播
			BroadcastToClient(&pb.S_Ntf_ItemsChanged{})
			Ev.OnMgrChangeUserOrChannel("change_game")
			return
		case nt.ZkP.Channels:
			// 广播
			BroadcastToClient(&pb.S_Ntf_ItemsChanged{})
			Ev.OnMgrChangeUserOrChannel("change_channel")
			return
		case nt.ZkP.ClientAddrs:
			BroadcastToClient(nt.DynConf.ClientAddrsConf)
			Ev.OnMgrChangeUserOrChannel("change_client_config")
			return
		}
		// 检查本节点数据变化
		// 仅仅支持离线，如果状态为已离线，则断开到 login 的连接。到 session 为0的时候，退出
		bytes, err := nt.Zk.GetNodeData(path)
		if nil != err {
			log.Warn("zk GetNodeData", zap.String("name", path), zap.Error(err))
			return
		}
		c := &conf.Conf{}
		err = json.Unmarshal(bytes, c)
		if nil != err {
			log.Warn("zk GetNodeData", zap.String("name", path), zap.Error(err))
		}
		if c.Online == 0 {
			Online = 0
		}
	} else {
		// 属于不受支持的情况，统统报错
		log.Warn("lobby node", zap.String("err", "event not supported currently"))
	}
}
