ChainsawFuelEvent = {}
local ChainsawFuelEvent_mt = Class(ChainsawFuelEvent, Event)

InitEventClass(ChainsawFuelEvent, "ChainsawFuelEvent")

function ChainsawFuelEvent.emptyNew()
    local self = Event.new(ChainsawFuelEvent_mt)
    return self
end

function ChainsawFuelEvent.new(playerKey, fuel)
    local self = ChainsawFuelEvent.emptyNew()
    self.playerKey = playerKey
    self.fuel = fuel
    return self
end

function ChainsawFuelEvent:readStream(streamId, connection)
    self.playerKey = streamReadString(streamId)
    self.fuel = streamReadFloat32(streamId)
    self:run(connection)
end

function ChainsawFuelEvent:writeStream(streamId, connection)
    streamWriteString(streamId, self.playerKey)
    streamWriteFloat32(streamId, self.fuel)
end

function ChainsawFuelEvent:run(connection)
    local mission = g_currentMission
    if mission == nil or mission.chainsawFuelMod == nil then
        return
    end

    if g_server ~= nil and connection ~= nil and connection:getIsServer() == false then
        -- Never trust a client supplied player key. Bind the update to the
        -- authenticated connection so one player cannot alter another player.
        local userId = mission.userManager ~= nil and mission.userManager:getUserIdByConnection(connection) or nil
        if userId == nil then
            return
        end
        self.playerKey = "user_" .. tostring(userId)
        self.fuel = math.max(0, math.min(1, tonumber(self.fuel) or 0))
        mission.chainsawFuelMod:setFuelForPlayerKey(self.playerKey, self.fuel, true)
        g_server:broadcastEvent(ChainsawFuelEvent.new(self.playerKey, self.fuel), false, connection, mission)
    else
        self.fuel = math.max(0, math.min(1, tonumber(self.fuel) or 0))
        mission.chainsawFuelMod:setFuelForPlayerKey(self.playerKey, self.fuel, true)
    end
end
