require "TimedActions/ISBaseTimedAction"

-- Optional visual helper (will no-op if not present)
pcall(function() require "MSW_Visual" end)

MSW_ISLoadVehicle = ISBaseTimedAction:derive("MSW_ISLoadVehicle")

local TARGET_PART_ID = "ATAMultiSlotWrecker"

local function msw_applyVisual(trailer, forceVisible)
    if not trailer then return end
    local part = trailer:getPartById(TARGET_PART_ID)
    if not part then return end

    -- Prefer the visual helper (keeps logic in one place)
    if MSW_Visual and MSW_Visual.applyForVehicle then
        pcall(function() MSW_Visual.applyForVehicle(trailer) end)
        return
    end

    -- Fallback: simple toggle of the "Default" model
    if forceVisible ~= nil then
        pcall(function() part:setModelVisible("Default", forceVisible) end)
    end
end

local function msw_refreshSoon(trailer, ticks)
    ticks = ticks or 10 -- ~0.3s
    local function onTick()
        ticks = ticks - 1
        if ticks <= 0 then
            msw_applyVisual(trailer, nil) -- pull latest modData-based state
            Events.OnTick.Remove(onTick)
        end
    end
    Events.OnTick.Add(onTick)
end

function MSW_ISLoadVehicle:isValid()
    return self.trailer and not self.trailer:isRemovedFromWorld()
end

function MSW_ISLoadVehicle:update()
    self.character:faceThisObject(self.trailer)
    self.character:setMetabolicTarget(Metabolics.HeavyWork)
end

function MSW_ISLoadVehicle:start()
    setGameSpeed(1)
    self:setActionAnim("Loot")
    self.trailer:getEmitter():playSound("ATAVehicleWrecker")
end

function MSW_ISLoadVehicle:stop()
    self.trailer:getEmitter():stopSoundByName("ATAVehicleWrecker")
    ISBaseTimedAction.stop(self)
end

function MSW_ISLoadVehicle:perform()
    -- Send server command
    sendClientCommand(self.character, 'msw', 'loadVehicle', {
        trailer = self.trailer:getId(),
        vehicle = self.vehicle and self.vehicle:getId() or nil,
        slot = self.slotIndex
    })

    -- Tiny refresh: immediately show the Default model (we know a slot will be occupied)
    msw_applyVisual(self.trailer, true)
    -- And refresh again shortly after server syncs modData down
    msw_refreshSoon(self.trailer, 12)

    setGameSpeed(1)
    self.trailer:getEmitter():stopSoundByName("ATAVehicleWrecker")
    ISBaseTimedAction.perform(self)
end

function MSW_ISLoadVehicle:new(character, trailer, vehicle, slotIndex)
    local o = {}
    setmetatable(o, self)
    self.__index = self
    o.character = character
    o.trailer = trailer
    o.vehicle = vehicle
    o.slotIndex = slotIndex
    o.maxTime = 330
    if character:isTimedActionInstant() then o.maxTime = 10 end
    return o
end