--[[
    Helicopter Network Event
    Copyright (C) Lambo Mods, 2025
    Based on Mr Chow Modding's network event pattern
    
    Handles client-server input synchronization for multiplayer
]]

HelicopterNetworkEvent = {}
local HelicopterNetworkEvent_mt = Class(HelicopterNetworkEvent, Event)
InitEventClass(HelicopterNetworkEvent, "HelicopterNetworkEvent")

function HelicopterNetworkEvent.emptyNew()
    local self = Event.new(HelicopterNetworkEvent_mt)
    return self
end

function HelicopterNetworkEvent.new(vehicle, forward, back, left, right, yawLeft, yawRight, climb, descend)
    local self = HelicopterNetworkEvent.emptyNew()
    self.vehicle = vehicle
    self.forward = forward or false
    self.back = back or false
    self.left = left or false
    self.right = right or false
    self.yawLeft = yawLeft or false
    self.yawRight = yawRight or false
    self.climb = climb or false
    self.descend = descend or false
    return self
end

function HelicopterNetworkEvent:writeStream(streamId, connection)
    NetworkUtil.writeNodeObject(streamId, self.vehicle)
    streamWriteBool(streamId, self.forward)
    streamWriteBool(streamId, self.back)
    streamWriteBool(streamId, self.left)
    streamWriteBool(streamId, self.right)
    streamWriteBool(streamId, self.yawLeft)
    streamWriteBool(streamId, self.yawRight)
    streamWriteBool(streamId, self.climb)
    streamWriteBool(streamId, self.descend)
end

function HelicopterNetworkEvent:readStream(streamId, connection)
    self.vehicle = NetworkUtil.readNodeObject(streamId)
    self.forward = streamReadBool(streamId)
    self.back = streamReadBool(streamId)
    self.left = streamReadBool(streamId)
    self.right = streamReadBool(streamId)
    self.yawLeft = streamReadBool(streamId)
    self.yawRight = streamReadBool(streamId)
    self.climb = streamReadBool(streamId)
    self.descend = streamReadBool(streamId)
    self:run(connection)
end

function HelicopterNetworkEvent:run(connection)
    if not connection:getIsServer() then
        g_server:broadcastEvent(
            HelicopterNetworkEvent.new(self.vehicle, self.forward, self.back, self.left, self.right, self.yawLeft, self.yawRight, self.climb, self.descend),
            nil, connection, self.vehicle
        )
    end
    
    -- Apply inputs directly to vehicle (compatible with Helicopter.lua)
    if self.vehicle ~= nil then
        self.vehicle.heliInputForward = self.forward
        self.vehicle.heliInputBack = self.back
        self.vehicle.heliInputLeft = self.left
        self.vehicle.heliInputRight = self.right
        self.vehicle.heliInputYawLeft = self.yawLeft
        self.vehicle.heliInputYawRight = self.yawRight
        self.vehicle.heliInputClimb = self.climb
        self.vehicle.heliInputDescend = self.descend
    end
end
