require "TimedActions/ISBaseTimedAction"
ReloadMainGunAction = ISBaseTimedAction:derive("ReloadMainGunAction");

function ReloadMainGunAction:isValid()
    return true
end

function ReloadMainGunAction:update()
    self.startTick = self.startTick + 1

    if self.startTick == 50 then
        self.character:playSound(PanzerList[self.PanzerType].LoadSoundLoading)
    end
    if self.startTick == 100 then
        self.character:playSound("ShellDrop")
    end
end

function ReloadMainGunAction:start()
    self.character:playSound(PanzerList[self.PanzerType].LoadSoundStart)
end

function ReloadMainGunAction:stop()
    ISBaseTimedAction.stop(self);
    self.character:playSound(PanzerList[self.PanzerType].LoadSoundEnd)
end

local function hasAmmo(vehicle, AmmoType, PanzerType)
    for k, v in pairs(PanzerList[PanzerType].AmmoCache) do
        if k == "Normal" then
            local AmmoBox = vehicle:getPartById(PanzerType .. "_AmmoCache")
            if AmmoBox then
                local inv = AmmoBox:getItemContainer()
                local Ammo = inv:FindAndReturn(AmmoType)
                if Ammo then
                    return true
                end
            end
        else
            local modData = vehicle:getModData()
            if modData.researchTable and modData.researchTable[k] then
                local AmmoBox = vehicle:getPartById(PanzerType .. "_AmmoCacheBig")
                if AmmoBox then
                    local inv = AmmoBox:getItemContainer()
                    local Ammo = inv:FindAndReturn(AmmoType)
                    if Ammo then
                        return true
                    end
                end
            end
        end
    end
    return false
end

function ReloadMainGunAction:removeTargetAmmo(AmmoType)

    for k, v in pairs(PanzerList[self.PanzerType].AmmoCache) do
        if k == "Normal" then
            local AmmoBox = self.vehicle:getPartById(self.PanzerType .. "_AmmoCache")
            if AmmoBox then
                local inv = AmmoBox:getItemContainer()
                local Ammo = inv:FindAndReturn(AmmoType)
                if Ammo then
                    inv:Remove(Ammo)
                    inv:removeItemOnServer(Ammo)
                end
            end
        else
            local modData = self.vehicle:getModData()
            if modData.researchTable and modData.researchTable[k] then
                local AmmoBox = self.vehicle:getPartById(self.PanzerType .. "_AmmoCacheBig")
                if AmmoBox then
                    local inv = AmmoBox:getItemContainer()
                    local Ammo = inv:FindAndReturn(AmmoType)
                    if Ammo then
                        inv:Remove(Ammo)
                        inv:removeItemOnServer(Ammo)
                    end
                end
            end
        end
    end
end

function ReloadMainGunAction:perform()
    ISBaseTimedAction.perform(self);
    self.character:playSound(PanzerList[self.PanzerType].LoadSoundEnd)
    local vehicle = self.character:getVehicle()
    local modData = vehicle:getModData()
    modData.PanzerReadyToFire = true
    local CrewLaungage = PanzerList[self.PanzerType].CrewLaungage
    if self.character:getModData().CrewLaungage then
        CrewLaungage = self.character:getModData().CrewLaungage
    end
    if self.ammoType == "AP" then
        self.character:playSound(CrewLaungage .. "Panzer_Crew_LoadComplete_AP")
        modData.PanzerLoadNow = "AP"
        self:removeTargetAmmo(self.AmmoItem)
    elseif self.ammoType == "HE" then
        self.character:playSound(CrewLaungage .. "Panzer_Crew_LoadComplete_HE")
        modData.PanzerLoadNow = "HE"
        self:removeTargetAmmo(self.AmmoItem)
    end

end

function ReloadMainGunAction:new(character, ammoType, PanzerType, AmmoItem)
    local o = {}
    setmetatable(o, self)
    self.__index = self
    o.character = character;
    o.PanzerType = PanzerType;
    o.AmmoItem = AmmoItem;
    o.stopOnWalk = false;
    o.vehicle = character:getVehicle();
    o.ammoType = ammoType
    o.stopOnRun = false;
    o.maxTime = 200 - (50 * (GetAbilityLevel(character:getVehicle(), "FastLoad") / 10));
    o.startTick = 0
    return o;
end

local function LaunchNewAction(_player, ammoType, CrewLaungage, AmmoItem)
    ISTimedActionQueue.add(ReloadMainGunAction:new(_player, ammoType, CrewLaungage, AmmoItem))
end

local function StartTigerIIReloadAction(key)
    local playerObj = getPlayer()
    local inv = playerObj:getInventory()
    local vehicle = playerObj:getVehicle()
    if not vehicle then
        return
    end
    if key == getKeyCode("R") then
        local part = vehicle:getPartById("M1A1_Turret")
        vehicle:playPartAnim(part, "Open")
    end
    local PanzerType = GetPanzerType(vehicle)
    if (PanzerType) and vehicle:getSeat(playerObj) == 0 then
        local CrewLaungage = PanzerList[PanzerType].CrewLaungage
        if playerObj:getModData().CrewLaungage then
            CrewLaungage = playerObj:getModData().CrewLaungage
        end
        if key == getKeyCode("R") then
            if PanzerList[PanzerType].MainGunIsMG then
                return
            end
            local modData = vehicle:getModData()
            if not modData.PanzerReadyToFire then
                modData.PanzerReadyToFire = false
            end
            if modData.PanzerReadyToFire then
                return
            end
            if not modData.PanzerReadyToFire then
                if not modData.AmmoTypeNow then
                    modData.AmmoTypeNow = "AP"
                end

                local AmmoItemNeed = PanzerList[PanzerType].AmmoType[modData.AmmoTypeNow]
                if not AmmoItemNeed then
                    playerObj:Say(getText("IGUI_NoAmmoSelected"))
                    return
                end
                if modData.AmmoTypeNow == "AP" or modData.AmmoTypeNow == "APFSDS" then
                    if hasAmmo(vehicle, AmmoItemNeed, PanzerType) then
                        playerObj:playSound(CrewLaungage .. "Panzer_Crew_LoadAP")
                        LaunchNewAction(playerObj, "AP", PanzerType, AmmoItemNeed)
                    else
                        playerObj:Say(getText("IGUI_NoAmmo"))
                    end
                end
                if modData.AmmoTypeNow == "HE" then
                    if hasAmmo(vehicle, AmmoItemNeed, PanzerType) then
                        playerObj:playSound(CrewLaungage .. "Panzer_Crew_LoadHE")
                        LaunchNewAction(playerObj, "HE", PanzerType, AmmoItemNeed)
                    else
                        playerObj:Say(getText("IGUI_NoAmmo"))
                    end
                end
            end

        end
    end
end

local function TigerIIMainGunFire(playerObj)
    local vehicle = playerObj:getVehicle()
    local modData = playerObj:getModData()

    if modData.WirbelwindVehicleId and not isMouseButtonDown(1) then
        if modData.WirbelwindVehicleId then
            local vehicle = getVehicleById(modData.WirbelwindVehicleId)
            playerObj:setVehicle(vehicle)
            modData.WirbelwindVehicleId = nil
        end
    end
    if not vehicle then
        return
    end
    local PanzerType = GetPanzerType(vehicle)
    if (vehicle and PanzerType) and vehicle:getSeat(playerObj) == 0 then
        if isMouseButtonDown(1) then
            local Drag = getCell():getDrag(0)
            if Drag and (Drag.type == "Panzer" or Drag.type == "PanzerMG") then
                return
            end
            if PanzerMGEnable then
                local AimCursor = ISPanzerMG34AimingCursor:new("", "", playerObj)
                getCell():setDrag(AimCursor, 0)
            else
                if PanzerList[PanzerType].MainGunIsMG then

                    if PanzerType == "Gepard1A2" and vehicle:getModData().AmmoTypeNow == "AniTiTankMissle" then
                        local AimCursor = ISPanzerRocketAimingCursor:new("", "", playerObj)
                        getCell():setDrag(AimCursor, 0)
                        return
                    end

                    local AimCursor = ISPanzerAAAimingCursor:new("", "", playerObj)
                    getCell():setDrag(AimCursor, 0)
                else
                    local AimCursor = ISPanzerAimingCursor:new("", "", playerObj)
                    getCell():setDrag(AimCursor, 0)
                end

            end

        else
            local Drag = getCell():getDrag(0)
            if Drag and (Drag.type == "Panzer" or Drag.type == "PanzerMG") then
                getCell():setDrag(nil, 0)
                if Drag.instance then
                    Drag.instance = nil
                end
            end
        end
    elseif vehicle and PanzerType and (vehicle:getSeat(playerObj) == 2) then
        if isMouseButtonDown(1) then
            local Drag = getCell():getDrag(0)
            if PanzerList[PanzerType].MainGunIsMG then
                return
            end
            if Drag and (Drag.type == "Panzer" or Drag.type == "PanzerMG") then
                return
            end

            local AimCursor = ISPanzerMG42AimingCursor:new("", "", playerObj)
            getCell():setDrag(AimCursor, 0)

        else

            local Drag = getCell():getDrag(0)
            if Drag and (Drag.type == "Panzer" or Drag.type == "PanzerMG") then
                getCell():setDrag(nil, 0)
                if Drag.instance then
                    Drag.instance = nil
                end
            end
        end
    end
end

local function CheckLocal()
    Events.OnKeyPressed.Add(StartTigerIIReloadAction)
end

Events.OnPlayerUpdate.Add(TigerIIMainGunFire)

Events.OnGameStart.Add(CheckLocal)

