DiseaseThreatNotificationEvent = {}
local DiseaseThreatNotificationEvent_mt = Class(DiseaseThreatNotificationEvent, Event)
InitEventClass(DiseaseThreatNotificationEvent, "DiseaseThreatNotificationEvent")

function DiseaseThreatNotificationEvent.emptyNew()
    return Event.new(DiseaseThreatNotificationEvent_mt)
end

function DiseaseThreatNotificationEvent.new(text, farmId)
    local self = DiseaseThreatNotificationEvent.emptyNew()
    self.text = text or ""
    self.farmId = farmId
    return self
end

function DiseaseThreatNotificationEvent:writeStream(streamId, _)
    streamWriteString(streamId, tostring(self.text or ""))
    streamWriteBool(streamId, self.farmId ~= nil)
    if self.farmId ~= nil then
        streamWriteUIntN(streamId, math.max(0, tonumber(self.farmId) or 0), FarmManager.FARM_ID_SEND_NUM_BITS)
    end
end

function DiseaseThreatNotificationEvent:readStream(streamId, connection)
    self.text = streamReadString(streamId)
    if streamReadBool(streamId) then
        self.farmId = streamReadUIntN(streamId, FarmManager.FARM_ID_SEND_NUM_BITS)
    else
        self.farmId = nil
    end
    self:run(connection)
end

function DiseaseThreatNotificationEvent:run(_)
    if g_server ~= nil then
        return
    end

    if self.farmId ~= nil and g_currentMission ~= nil and g_currentMission.getFarmId ~= nil and g_currentMission:getFarmId() ~= self.farmId then
        return
    end

    if DiseaseCore ~= nil and DiseaseCore.showThreatNotificationText ~= nil then
        DiseaseCore:showThreatNotificationText(self.text)
    elseif g_dedicatedServer ~= true and self.text ~= nil and self.text ~= "" and g_currentMission ~= nil and g_currentMission.addIngameNotification ~= nil and FSBaseMission ~= nil then
        local notificationType = FSBaseMission.INGAME_NOTIFICATION_CRITICAL
            or FSBaseMission.INGAME_NOTIFICATION_WARNING
            or FSBaseMission.INGAME_NOTIFICATION_INFO

        if notificationType ~= nil then
            g_currentMission:addIngameNotification(notificationType, self.text)
        end
    end
end

function DiseaseThreatNotificationEvent.broadcast(text, farmId)
    if g_server ~= nil and text ~= nil and text ~= "" then
        g_server:broadcastEvent(DiseaseThreatNotificationEvent.new(text, farmId), false)
    end
end
