--[[Copyright (C) Mr Chow Modding, 2025]]
--===============================================================
     -- Helicopter script For FS25 --
--===============================================================
-- Made by Mr Chow Modding
-- Controls:
-- W / A / S / D – Tilt forward, left, backward, right
-- Q / R – Yaw left / right
-- LMB / RMB – Increase / decrease vertical thrust
-- Left Shift – Increase / decrease pitch (boost)
-- Left Ctrl – Toggle auto hover
-- I – Cycle HUD modes (first-person view only)
HelicopterInputEvent = {}
local HelicopterInputEvent_mt = Class(HelicopterInputEvent, Event)
InitEventClass(HelicopterInputEvent, "HelicopterInputEvent")

function HelicopterInputEvent.emptyNew()
    local self = Event.new(HelicopterInputEvent_mt)
    return self
end

-- Order must match the call in HelicopterMode:onUpdate:
--   sc:sendEvent(HelicopterInputEvent.new(self, w, s, a, d, q, r, lmb, rmb))
function HelicopterInputEvent.new(vehicle, w, s, a, d, q, r, lmb, rmb)
    local self = HelicopterInputEvent.emptyNew()
    self.vehicle = vehicle
    self.w, self.s = w or false, s or false
    self.a, self.d = a or false, d or false
    self.q, self.r = q or false, r or false
    self.lmb, self.rmb = lmb or false, r or false and rmb
    self.lmb, self.rmb = lmb or false, rmb or false
    return self
end

function HelicopterInputEvent:writeStream(streamId, connection)
    NetworkUtil.writeNodeObject(streamId, self.vehicle)
    streamWriteBool(streamId, self.w)
    streamWriteBool(streamId, self.s)
    streamWriteBool(streamId, self.a)
    streamWriteBool(streamId, self.d)
    streamWriteBool(streamId, self.q)
    streamWriteBool(streamId, self.r)
    streamWriteBool(streamId, self.lmb)
    streamWriteBool(streamId, self.rmb)
end

function HelicopterInputEvent:readStream(streamId, connection)
    self.vehicle = NetworkUtil.readNodeObject(streamId)
    self.w   = streamReadBool(streamId)
    self.s   = streamReadBool(streamId)
    self.a   = streamReadBool(streamId)
    self.d   = streamReadBool(streamId)
    self.q   = streamReadBool(streamId)
    self.r   = streamReadBool(streamId)
    self.lmb = streamReadBool(streamId)
    self.rmb = streamReadBool(streamId)
    self:run(connection)
end

function HelicopterInputEvent:run(connection)
    if not connection:getIsServer() then
        g_server:broadcastEvent(
            HelicopterInputEvent.new(self.vehicle, self.w, self.s, self.a, self.d, self.q, self.r, self.lmb, self.rmb),
            nil, connection, self.vehicle
        )
    end
    if self.vehicle ~= nil and self.vehicle.setHelicopterInput ~= nil then
        -- Mode expects: setHelicopterInput(w, s, q, r, a, d, lmb, rmb)
        self.vehicle:setHelicopterInput(self.w, self.s, self.q, self.r, self.a, self.d, self.lmb, self.rmb)
    end
end
