RealisticDieselPriceEvent = {}
local RealisticDieselPriceEvent_mt = Class(RealisticDieselPriceEvent, Event)
InitEventClass(RealisticDieselPriceEvent, "RealisticDieselPriceEvent")

function RealisticDieselPriceEvent.emptyNew()
    return Event.new(RealisticDieselPriceEvent_mt)
end

function RealisticDieselPriceEvent.new(state)
    local self = RealisticDieselPriceEvent.emptyNew()
    self.state = state or (RealisticDieselPrice ~= nil and RealisticDieselPrice.currentState) or 1
    return self
end

function RealisticDieselPriceEvent:writeStream(streamId, connection)
    streamWriteUInt8(streamId, self.state)
end

function RealisticDieselPriceEvent:readStream(streamId, connection)
    self.state = streamReadUInt8(streamId)
    self:run(connection)
end

local function isAuthorized(connection)
    if g_currentMission == nil or g_currentMission.userManager == nil then return false end
    local userId = g_currentMission.userManager:getUserIdByConnection(connection)
    if userId == nil then return false end
    local user = g_currentMission.userManager:getUserByUserId(userId)
    if user ~= nil and user.getIsMasterUser ~= nil and user:getIsMasterUser() then return true end
    local farm = g_farmManager ~= nil and g_farmManager:getFarmByUserId(userId) or nil
    return farm ~= nil and farm.isUserFarmManager ~= nil and farm:isUserFarmManager(userId)
end

function RealisticDieselPriceEvent:run(connection)
    if RealisticDieselPrice == nil then return end
    if g_server ~= nil and connection ~= nil and not connection:getIsServer() then
        if not isAuthorized(connection) then
            connection:sendEvent(RealisticDieselPriceEvent.new(RealisticDieselPrice.currentState))
            return
        end
        RealisticDieselPrice:setState(self.state, true)
        g_server:broadcastEvent(RealisticDieselPriceEvent.new(RealisticDieselPrice.currentState), false, connection)
    else
        RealisticDieselPrice:setState(self.state, false)
    end
end

function RealisticDieselPriceEvent.sendToServer(state)
    if g_client ~= nil and g_server == nil then
        g_client:getServerConnection():sendEvent(RealisticDieselPriceEvent.new(state))
    end
end

function RealisticDieselPriceEvent.sendToClients()
    if g_server ~= nil then
        g_server:broadcastEvent(RealisticDieselPriceEvent.new(RealisticDieselPrice.currentState))
    end
end
