-- 跨服鏈接和重连管理
local msg_parse = _G.msg_inner_parse
local Config = require("Config")
local Log = require("common.Log")
local CommonDB = require("common.CommonDB")
local InnerMsg = require("core.InnerMsg")
local MiddleManager = require("middle.MiddleManager")
local MiddleHeartBeat = require("middle.MiddleHeartBeat")
local Define = require("platform.Define")
local Json = require("common.Json")
local JjcLadderMiddle = require("jjcLadder.JjcLadderMiddle")

IS_MIDDLE_CONNECT = IS_MIDDLE_CONNECT or nil -- 是否連上跨服 收到WLhello才認為連上了

YY_ACT_FLAG = nil

-- 请求middleInfo
local s2aParam = {}
local function questMiddleInfo()
    s2aParam.sid = Config.SVR_INDEX
	s2aParam.api_cbMethod = "setMiddleInfo"
    _G.thread_http.send(Define.MIDDLE_INFO_URL, Json.Encode(s2aParam))
end


function setMiddleInfo(ip, port, host)
	if _G.is_middle == true then return end

    local middleDBInfo = CommonDB.getMiddleInfo()
	if middleDBInfo.ip == ip and middleDBInfo.port == port and middleDBInfo.host == host then
		-- 沒變化
		return
	end

    local oldIp = middleDBInfo.ip
    local oldPort = middleDBInfo.port

    CommonDB.setMiddleInfo(ip, port, host)
	if oldIp == ip and oldPort == port then
    	-- 只有host变了 不需要重連
    	return
    else
        tryConnectMiddle(ip, port) -- try的時候會把之前的鏈接斷開
   	end
end

function getMiddleInfo()
	--调试模式使用配置的IP
    if Config.IS_DEBUG then
        return Config.MIDDLE_IP, Config.MIDDLE_PORT, Config.MIDDLE_HOST
    end

    local middleDBInfo = CommonDB.getMiddleInfo()
    return middleDBInfo.ip, middleDBInfo.port, middleDBInfo.host
end

function initAfterStart()
    onTimer() -- 啟動拉取一下middleInfo
end

function onTimer()
	if _G.is_middle == true then return end

	-- 如果没有middleip 去找后台请求middleip 1分钟1次
	local ip, port = getMiddleInfo()
	if ip == nil then
		-- reyes todo get ip
        print("no middleInfo try to get")
        questMiddleInfo()
		return
	end

	-- 如果ip有了 但是一直没连上 1分钟重连1次
    if isConnect() ~= true then
        tryConnectMiddle(ip, port)
		return
	end

	-- 如果3分钟之内 没有收到middle的心跳包 并且底层还是连接中的状态 我们认为出故障了 这个时候重连一下middle 这是一个异常处理
    if MiddleHeartBeat.LAST_HEARTBEAT_TIME then
	    local now = os.time()
        if now - MiddleHeartBeat.LAST_HEARTBEAT_TIME > 180 then
            stopConnectMiddle()
        end
    end
end

function autoResetMiddle()
    if _G.is_middle == true then return end

    -- 每周一凌晨2點 斷開鏈接 并且重新取一下php的跨服信息 重新連新跨服
    CommonDB.setMiddleInfo(nil, nil, nil)

    stopConnectMiddle()

    onTimer() -- 拉取一下middleInfo
end


function isConnect()
    -- 這個接口和IS_MIDDLE_CONNECT的區別是 這個表示底層鏈接連上了 但是不一定正確收到了middle會包 lua層業務判斷最好別用這個接口 盡量用IS_MIDDLE_CONNECT
    local ret = msg_parse.check_connect()
    if ret == true then
        return true
    end
end

function tryConnectMiddle(ip, port)
    print("try connect middle ", ip, port)
    Log.write(Log.LOGID_INNER_CLOSE, "tryConnectMiddle", ip, port)
    msg_parse.set_connect(ip, port)
end

function stopConnectMiddle()
    print("stop connect middle ")
    Log.write(Log.LOGID_INNER_CLOSE, "stopConnectMiddle")
    msg_parse.close_connect()

    IS_MIDDLE_CONNECT = nil
    MiddleHeartBeat.LAST_HEARTBEAT_TIME = nil
    MiddleHeartBeat.LAST_SEND_HB_TS = nil
end

function LW_HELLO(fd, msg)
    print("LW Hello")
    Log.write(Log.LOGID_INNER_CLOSE, "LW_HELLO")

    MiddleManager.addLogicServer(fd, msg.svrIndex)

    local msg = InnerMsg.wl.WL_HELLO
    InnerMsg.sendMsg(fd, msg)

    msg = InnerMsg.wl.WL_HEARTBEAT
    InnerMsg.sendMsg(fd, msg)
    
    -- 同步其它信息
    JjcLadderMiddle.sendWLMobaiCnt(fd)
end

function WL_HELLO(fd, msg)
    print("WL hello")
    Log.write(Log.LOGID_INNER_CLOSE, "WL_HELLO")

    if not IS_MIDDLE_CONNECT then
        print("middle server upup!!!---")
        IS_MIDDLE_CONNECT = true

        local openTime = CommonDB.getServerOpenTime()
        if openTime ~= 0 then
            local msg = InnerMsg.lw.LW_SET
            msg.openTime = openTime or 0
            msg.svrIndex = Config.SVR_INDEX
            InnerMsg.sendMsg(fd, msg)
        end
    end
end

function LW_SET(fd,msg)
    MiddleManager.setServerOpenDay(fd,msg.svrIndex,msg.openTime)
end

function LW_DISCONNECT(fd, msg)  
    print("LW_DISCONNECT")
  
    MiddleManager.delLogicServer(fd) 
end

--middle断线，C++层触发
function WL_DISCONNECT(fd, msg)
    if IS_MIDDLE_CONNECT then
        IS_MIDDLE_CONNECT = nil
        MiddleHeartBeat.LAST_HEARTBEAT_TIME = nil
        MiddleHeartBeat.LAST_SEND_HB_TS = nil

        Log.write(Log.LOGID_INNER_CLOSE, "middle server disconnect!!!")
        print("middle server disconnect!!!---")
    end
end
