require "Insurgent/InsurgentTraitDefinitions"

BloodFrenzyTrait = CreateInsurgentTrait()
BloodFrenzyTrait.name = "BloodFrenzy"
BloodFrenzyTrait.insurgentExclusive = true

function BloodFrenzyTrait.Create()
    return TraitFactory.addTrait("BloodFrenzy", getText("UI_trait_BloodFrenzy"), 8, getText("UI_trait_BloodFrenzyDesc"), false, false);
end

function BloodFrenzyTrait.OnNewGame(player)
    if not player:HasTrait("BloodFrenzy") then
        return
    end
    
    local playerdata = player:getModData();
    playerdata.comboHits = 0;
    playerdata.frenzyTimer = 0;
end

function BloodFrenzyTrait.OnPlayerUpdate(player)
    if not player:HasTrait("BloodFrenzy") or not player:isLocalPlayer() then
        return
    end

    local playerdata = player:getModData();
    if playerdata.frenzyTimer <= 0 and playerdata.comboHits > 0 then
        playerdata.comboHits = 0;
    elseif playerdata.frenzyTimer > 0 then
        playerdata.frenzyTimer = playerdata.frenzyTimer - 1;
    end
end

function BloodFrenzyTrait.OnWeaponHitCharacter(attacker, target, weapon, damage)
    if not attacker:HasTrait("BloodFrenzy") then
        return
    end
    
    if weapon:getName() == "Bare Hands" then
        return
    end
    
    local stats = attacker:getStats();
    local attackerData = attacker:getModData();

    local addedDamage = attackerData.comboHits / 100;
    if attackerData.frenzyTimer <= 0 then
        if getCore():getOptionMusicVolume() ~= 0 and not getSoundManager():isPlayingMusic() then
            getSoundManager():playMusic(MusicChoices.get(100));
        end

    end
    
    attackerData.frenzyTimer = 500;

    if target:isZombie() then
        target:setHealth(target:getHealth() - addedDamage);
    end

    if stats:getAnger() < addedDamage then
        stats:setAnger(addedDamage);
    end

    attackerData.comboHits = attackerData.comboHits + 1;
end


function BloodFrenzyTrait.RegisterEvents()
    Events.OnNewGame.Add(BloodFrenzyTrait.OnNewGame)
    Events.OnPlayerUpdate.Add(BloodFrenzyTrait.OnPlayerUpdate)
    Events.OnWeaponHitCharacter.Add(BloodFrenzyTrait.OnWeaponHitCharacter)
end