require "VanCreate"

Panzer = Panzer or {};
PanzerArmor = PanzerArmor or {};

function Panzer:sendVehicleCommandWrapper(player, part, methodName, args)
    local args = args or {}
    args.part = part:getId()
    args.vehicle = part:getVehicle():getId()
    sendClientCommand(player, "vehicle", methodName, args)
end

function Panzer:sendArmorCommandWrapper(player, part, methodName, args)
    local args = args or {}
    args.part = part:getId()
    args.vehicle = part:getVehicle():getId()
    sendClientCommand(player, "Panzer_armor", methodName, args)
end

function PanzerArmor.activeArmor()
    local player = getPlayer()
    if not player then
        return
    end
    local vehicle = player:getVehicle()
    if not vehicle then
        return
    end
    if vehicle:getDriver() ~= player then
        return
    end
    if (vehicle and GetPanzerType(vehicle)) then
        local Type = GetPanzerType(vehicle)
        local MaxArmorPressure = PanzerList[Type].MaxArmorPotection
        if HasUnlockThisReasearch(vehicle, "MoreArmor") then
            MaxArmorPressure = MaxArmorPressure + 20
        end
        for i = 1, vehicle:getPartCount() do
            local part = vehicle:getPartByIndex(i - 1)
            if part:getCondition() < MaxArmorPressure then
                Panzer:sendVehicleCommandWrapper(player, part, "setPartCondition", {
                    condition = MaxArmorPressure
                })
            end

        end
    end
end

local EnterFlag = false
local function CheckLocalVehicle()
    local player = getPlayer()
    if player then
        local vehicle = player:getVehicle()
        if (vehicle and GetPanzerType(vehicle)) and not EnterFlag then
            EnterFlag = true
            Events.OnPlayerUpdate.Add(PanzerArmor.activeArmor);
        else
            Events.OnPlayerUpdate.Remove(PanzerArmor.activeArmor);
            EnterFlag = false
        end
    end

end

Events.EveryOneMinute.Add(CheckLocalVehicle)
