// priority: 11
PlayerEvents.loggedIn(event => {
    let player = event.player
    if(!player)return
    for (let i = 0; i < 36; i++) {
        let stack = player.inventory.getStackInSlot(i)
        if (stack.id == 'pasterdream:dreamnotes_0') {
            stack.count = 0
        }
    }

})
//如果深渊触手的父实体有null_attack_addition持久话数据，也往子实体塞入null_attack_addition
EntityEvents.spawned(event => {
    let entity = event.entity
    // 仅处理深渊触手实体
    if (entity instanceof $Tidal_Tentacle_Entity) {
        entity.server.scheduleInTicks(3, () => {
            let tentacle = entity;
            // 使用 getFromEntity() 方法获取父实体
            let parentEntity = tentacle.getFromEntity();
            // 父实体存在且有null_attack_addition数据时，复制给子实体
            if (parentEntity && parentEntity.persistentData.contains('null_attack_addition')) {
                let attackAddition = parentEntity.persistentData.getInt('null_attack_addition');
                tentacle.persistentData.putInt('null_attack_addition', attackAddition);
            }
        })
    }
});
//具有特定nbt的实体造成伤害，取消伤害改为无源伤害
NativeEvents.onEvent($LivingAttackEvent, event => {
    let entity = event.source.immediate
    if (entity) {
        if (entity.persistentData.contains('null_attack_addition')) {
            let damage = entity.persistentData.getInt('null_attack_addition')
            simpleAttackEntity(true, null, event.entity, 'common', damage)
            event.setCanceled(true)
        }
    }
})
//玩家定身术持续时间改为2秒
NativeEvents.onEvent($MobEffectEvent$Applicable, event => {
    let player = event.entity
    if (!player.isPlayer()) return;
    if (player.level.clientSide) return

    // 获取buff
    let effectInstance = event.getEffectInstance()
    let buff = effectInstance.getEffect().getDescriptionId();

    if (buff == 'effect.jerotes.hold_mob') {
        event.getEffectInstance().setDuration(40)
    }
})
//玩家重生回满血
PlayerEvents.respawned(event => {
    let player = event.player;
    if (!player) return;
    player.server.scheduleInTicks(1, () => {
        player.setHealth(player.getMaxHealth())
    })
})
//玩家在帕斯特之梦最终boss的维度免疫摔落伤害
NativeEvents.onEvent($LivingHurtEvent, event => {
    if (event.entity.isPlayer()) {
        let player = event.entity
        let type = event.getSource().getType().toString()
        if (type == 'fall' && player.level.dimension == 'pasterdream:aaroncos_arena_world') {
            event.amount = 0
        }
    }
})
//防止未知bug
NativeEvents.onEvent($LivingHurtEvent, event => {
    if (event.amount == null || event.amount == Infinity) {
        event.amount = 0
        event.player.tell('检测到错误数值')
        event.player.tell('伤害来源：' + event.entity.type)
        event.player.tell('请反馈给作者')
    }
})
//禁止坎普斯生成
ServerEvents.loaded(event => {
    let server = event.server
    server.runCommandSilent('gamerule naughtinessMechanics false')
})
EntityEvents.spawned(event=>{
    let entity = event.entity.type
    if (entity == 'born_in_chaos_v1:krampus' || entity == 'born_in_chaos_v1:krampus_henchman'){
        event.cancel()
    }
})
//窥愿珍珠查看好感度
ItemEvents.rightClicked(event => {
    let player = event.player
    let item = event.item
    if (item.id == 'alexscaves:gazing_pearl') {
        player.tell(`好感度:${item.nbt.getInt('Reputation')}`)

    }
})
//火山核心挖掘
BlockEvents.broken(event => {
    if (event.block.id == 'alexscaves:volcanic_core') {
        event.block.popItem(Item.of('alexscaves:volcanic_core'))
    }
})
//禁止挖掘获取节点
BlockEvents.broken(event => {
    let player = event.getPlayer()
    let block = event.getBlock()
    if (block.id == 'alexscaves:azure_neodymium_node' || block.id == 'alexscaves:scarlet_neodymium_node') {
        player.tell('此方块已被禁止挖掘获取')
        player.tell('请合成以获取此方块')
        block.set('minecraft:air')
    }
})
//删除副手拐
NativeEvents.onEvent($ItemAttributeModifierEvent, event => {
    let stack = event.getItemStack();
    let modifiers = event.getModifiers();
    let attributes = modifiers.keySet().toArray();

    // 预加载所有可能用到的属性
    let drawStrengthAttribute = $TetraAttributes.drawStrength.get();
    let drawSpeedAttribute = $TetraAttributes.drawSpeed.get();
    let abilityDamage = $TetraAttributes.abilityDamage.get();
    let abilityCooldown = $TetraAttributes.abilityCooldown.get();
    let armor = $Attributes.ARMOR;
    let armorToughness = $Attributes.ARMOR_TOUGHNESS;

    for (let i = 0; i < attributes.length; i++) {
        let attribute = attributes[i];

        //tetra护甲处理
        if (stack.id == "hp_dzzl:modular_head" ||
            stack.id == "hp_dzzl:modular_chest" ||
            stack.id == "hp_dzzl:modular_legs" ||
            stack.id == "hp_dzzl:modular_feet"
        ) {
            //移除全部attribute
            event.removeAttribute(attribute);
        }
        // 弓和弩的处理
        if (stack.id == 'tetra:modular_bow' ||
            stack.id == 'tetra:modular_crossbow'
        ) {
            if (attribute != drawStrengthAttribute && attribute != drawSpeedAttribute) {
                event.removeAttribute(attribute);
            }
        }
        // 盾牌的处理
        else if (stack.id == 'tetra:modular_shield') {
            if (attribute != abilityDamage &&
                attribute != abilityCooldown &&
                attribute != armor &&
                attribute != armorToughness) {
                event.removeAttribute(attribute);
            }
        }
        // 其他物品的处理
        else {
            if (attribute == drawStrengthAttribute || attribute == drawSpeedAttribute) {
                event.removeAttribute(attribute);
            }
        }
    }
})
//buff消失移除召唤物
NativeEvents.onEvent($MobEffectEvent$Expired, event => {
    let entity = event.entity
    let effectInstance = event.getEffectInstance()
    let buff = effectInstance.getEffect().getDescriptionId()
    if (buff == 'effect.kubejs.enslavement') {
        entity.kill()
    }
})
//减少玩家受到的核爆伤害
NativeEvents.onEvent($LivingHurtEvent, event => {
    if (event.entity.isPlayer()) {
        if (event.getSource().getType().toString() == 'nuke') {
            event.amount = 10
        }
    }
})
//获取全部effect
//有益
const MAODLEFFECTS_BENEFICIAL = []
//有害
const MAODLEFFECTS_HARMFUL = []
for (let i = 0; $MobEffect.byId(i) != null; i++) {
    let currentEffect = $MobEffect.byId(i)
    if (currentEffect != null) {
        if ($MobEffect.byId(i).category == 'HARMFUL') {
            let descId = currentEffect.getDescriptionId()
            let slicedId = descId.slice(7);
            let standardId = slicedId.replace('.', ':');
            if (!MAODLEFFECTS_HARMFUL.includes(standardId)) {
                MAODLEFFECTS_HARMFUL.push(standardId);
            }
        } else if ($MobEffect.byId(i).category == 'BENEFICIAL') {
            let descId = currentEffect.getDescriptionId()
            let slicedId = descId.slice(7);
            let standardId = slicedId.replace('.', ':');
            if (!MAODLEFFECTS_BENEFICIAL.includes(standardId)) {
                MAODLEFFECTS_BENEFICIAL.push(standardId);
            }
        }
    }
}
//tetra盔甲汇总增伤
function tetra_wear_increased_damag(event) {
    let player = event.source.actual
    let tetra_wear_increased_damag = player.persistentData.getDouble('tetra_wear_increased_damag') ?? 0
    event.amount = event.amount * (1 + tetra_wear_increased_damag)
    player.persistentData.putDouble('tetra_wear_increased_damag', 0)
}
//最后统计增伤，把独立乘区改为基础乘法乘区
function mainhand_increased_damage(event) {
    let player = event.source.actual

    // 磁极—南增伤效果实现
    let item = player.getOffHandItem()
    if (item.item instanceof $ModularItem) {
        let effectLevel = simpleGetTetraEffectLevel(item, 'south_pole')
        if (effectLevel > 0) {
            let type = event.getSource().getType().toString();
            if (type == 'lightningBolt') {
                let currentDamage = player.persistentData.getDouble('mainhand_increased_damage_multiplication') || 0
                player.persistentData.putDouble(
                    'mainhand_increased_damage_multiplication',
                    currentDamage + effectLevel / 100
                )
            }
        }
    }

    let mainhandIncreased = player.persistentData.getDouble('mainhand_increased_damage_multiplication') || 0
    event.amount = event.amount * (1 + mainhandIncreased)
    // 重置数据
    player.persistentData.putDouble('mainhand_increased_damage_multiplication', 0)
}
//无花果藤新增获取方法
BlockEvents.rightClicked(event => {
    let player = event.player
    let item = player.getMainHandItem()
    let block = event.block
    if (item == 'minecraft:shears' && block == 'pasterdream:fig_vine') {
        block.set('minecraft:air')
        event.block.popItem('pasterdream:fig_vine')
    }
})
//空间宝石生成建筑
BlockEvents.rightClicked(event => {
    let player = event.player
    let item = player.getMainHandItem()
    if (event.hand != 'main_hand') return
    let x = Math.floor(player.x)
    let y = Math.floor(player.y)
    let z = Math.floor(player.z)
    if (item && item.nbt && item == 'kubejs:space_gem' && item.nbt.getInt('lll252')) {
        event.server.runCommandSilent(`place structure kubejs:lll252 ${x} ${y} ${z}`)
        item.shrink(1)
    }
})
//修复阴影高炉崩溃bug
BlockEvents.rightClicked(event => {
    let player = event.player
    let item = player.getMainHandItem()
    let block = event.block
    if (item == 'pasterdream:blueprint_0') {
        if (block == 'pasterdream:shadow_blast_furnace' || block == 'pasterdream:research_table') {
            player.tell('请勿拿图纸右键此方块，否则将导致崩溃')
            event.cancel()
        }
    }
})



//受伤时，tetra盔甲相关事件
function tetra_wear_event_2(event) {
    let player = event.entity
    let itemList = [
        player.getHeadArmorItem(),
        player.getChestArmorItem(),
        player.getLegsArmorItem(),
        player.getFeetArmorItem()
    ]
    itemList.forEach(item => {
        if (item.item instanceof $ModularItem) {
            let amount = Math.floor(event.amount / 4)
            //受伤减少耐久
            reduce_durability(item, amount)

            //打磨值增加
            item.item.tickProgression(player, item, 1)
        }
    })
}
//紫水晶蟹召唤
BlockEvents.rightClicked('minecraft:moss_block', event => {
    let player = event.player
    let item = player.getMainHandItem()
    let block = event.block
    if (item != 'minecraft:amethyst_block') return
    let spawn_entity = player.level.createEntity('cataclysm:amethyst_crab')
    spawn_entity.setPosition(block.x, block.y + 1, block.z)
    spawn_entity.spawn()
    item.shrink(1)
    event.cancel()
})


//玩家登录事件,去除玩家存储的冷却的持久话数据
PlayerEvents.loggedIn(event => {
    let player = event.player;
    if (!player) return;
    let count = 0
    global.all_effect.forEach(effect => {
        count++
        let amount = Math.floor(count / 50)
        player.getServer().scheduleInTicks(amount, () => {
            if (player.persistentData.contains(effect.effect_name)) {
                player.persistentData.remove(effect.effect_name);
            }
        })
    });
    player.persistentData.remove('pestilence_cd');
    player.persistentData.remove('ti_shi_cd');
});


//巨化与缩小等buff处理
PlayerEvents.tick(event => {
    let player = event.player
    if (player.age % 23 != 0 || !player) return;
    let total_effect = 0
    if (player.hasEffect('kubejs:ju_hua')) {
        // 获取已有的效果
        let effect = player.getEffect('kubejs:ju_hua')
        // 获取效果等级
        total_effect = total_effect + (effect.getAmplifier() + 1)
    }
    if (player.hasEffect('kubejs:living')) {
        // 获取已有的效果
        let effect = player.getEffect('kubejs:living')
        // 获取效果等级
        total_effect = total_effect + math.min((effect.getAmplifier() + 1) * 0.6, 8)
    }
    if (player.hasEffect('kubejs:suo_xiao')) {
        // 获取已有的效果
        let effect = player.getEffect('kubejs:suo_xiao')
        // 获取效果等级
        total_effect = total_effect - (effect.getAmplifier() + 1)
    }
    player.pehkui_getScaleData($ScaleTypes.BASE).setScale(1 + total_effect * 0.25)
    player.pehkui_getScaleData($ScaleTypes.HITBOX_HEIGHT).setScale(1 + total_effect * 0.25)
})


//检测是否有buff，将怪物的目标设置为自己
function ru_meng(event) {
    let entity = event.entity;
    if (!entity.target) return
    if (entity.hasEffect("kubejs:ru_meng")) {
        if (entity.target && entity.target.player) {
            event.setNewTarget(entity)
        }
    } else {
        if (entity.target === entity) {
            event.setNewTarget(null)
        }
    }
}

//增加生于混沌的boss传送CD
function born_in_chaos_boss_cd(event) {
    let entity = event.entity
    let name = entity.type
    if (entity && born_in_chaos_boss.includes(name)) {
        entity.potionEffects.add('born_in_chaos_v1:magic_depletion', 20 * 15, 0)
        entity.potionEffects.add('born_in_chaos_v1:block_break', 20 * 15, 0)
    }
}
////根据nbt增加造成的伤害
function attack_addition(event) {
    let entity = event.source.actual
    let entity_1 = event.source.immediate
    if (entity != null && entity.persistentData.contains('attack_addition')) {
        let damage = entity.persistentData.getInt('attack_addition')
        event.amount += damage
    }
    if (entity_1 != null && entity_1.persistentData.contains('attack_addition')) {
        let damage = entity_1.persistentData.getInt('attack_addition')
        event.amount += damage
    }
}
//使受到的自身的伤害为0
function playerattack_1(event) {
    let entity_1 = event.entity
    let entity_2 = event.source.actual
    if (entity_1.getUuid() == entity_2.getUuid() && entity_1.isPlayer() && entity_2.isPlayer()) {
        event.setCanceled(true)
    }
}

let $CreativeTabHandler = Java.loadClass("net.yiran.morerequirement.CreativeTabHandler")
ItemEvents.firstLeftClicked("tetra:scroll_rolled", event => {
    //$CreativeTabHandler.writeScrollData(event.item)
})
