import { world, system, MolangVariableMap } from "@minecraft/server";
import { projectileId as heatProjectileId, projectileCache as heatCache, handleHit as handleHeatHit } from "./TankProjectile.js";
import { projectileId as apfsdsProjectileId, projectileCache as apfsdsCache, handleHit as handleApfsdsHit } from "./APFSDSTankProjectile.js";
import { projectileId as heshProjectileId, projectileCache as heshCache, handleHit as handleHeshHit } from "./HESHTankProjectile.js";
import { VEHICLES } from "../VehiclesRoot.js";
import { reduceMainAmmo, getMainAmmo } from "../AmmoSystem.js";
import { shootProjectile } from "./TankProjectile.js";
import { shootProjectileHESH } from "./HESHTankProjectile.js";
import { shootProjectileAPFSDS } from "./APFSDSTankProjectile.js";
import { calculateShootLocationAndDirection } from "../ProjectileHelpers.js";

const dimensions = [
    world.getDimension("minecraft:overworld"),
    world.getDimension("minecraft:nether"),
    world.getDimension("minecraft:the_end"),
];

const FIRING_RATE = 10;
let isMainGunFiring = false;
let firingInterval = null;

world.afterEvents.itemStartUse.subscribe((event) => {
    const player = event.source;
    const item = event.itemStack;

    const tankTag = Array.from(player.getTags()).find(tag => tag.startsWith('tank_'));
    if (!tankTag) return;

    const tankId = tankTag.split('_')[1];
    const tank = player.dimension.getEntities().find(e => e.id === tankId);
    if (!tank) return;

    const vehicleConfig = Object.values(VEHICLES).find(v => v.identifier === tank.typeId);
    if (!vehicleConfig || (vehicleConfig.modelType !== "IFV_ROCKET" && vehicleConfig.modelType !== "IFV")) return;

    if (item?.typeId === vehicleConfig.mainGunItem) {
        if (firingInterval) {
            system.clearRun(firingInterval);
        }

        isMainGunFiring = true;
        firingInterval = system.runInterval(() => {
            const currentAmmo = getMainAmmo(tank);
            if (currentAmmo <= 0) {
                player.onScreenDisplay.setActionBar("§c没有弹药!");
                player.playSound("note.bass", { pitch: 1.0, volume: 1.0 });
                return;
            }

            const shellTag = Array.from(player.getTags()).find(tag =>
                tag === "heat_shell" ||
                tag === "apfsds_shell" ||
                tag === "phosphorus_shell"
            );
            if (!shellTag) {
                player.onScreenDisplay.setActionBar("§c请先选择子弹类型！");
                player.playSound("note.bass", { pitch: 0.5, volume: 1.0 });
                return;
            }

            if (reduceMainAmmo(tank)) {
                tank.playAnimation("animation.ifv_rocket107.fire_main");
                tank.dimension.spawnParticle("ttav:ground_smoke_aftermath_shoot_small",
                    { x: tank.location.x, y: tank.location.y+0.2, z: tank.location.z },
                    new MolangVariableMap()
                );
                player.runCommand(`/camerashake add @p[r=4] 0.02 0.02 rotational`);
                const [location, direction] = calculateShootLocationAndDirection(player);

                switch(shellTag) {
                    case "heat_shell":
                        shootProjectile(player, direction, location, 0);
                        break;
                    case "apfsds_shell":
                        shootProjectileAPFSDS(player, direction, location, 0);
                        break;
                    case "phosphorus_shell":
                        shootProjectileHESH(player, direction, location, 0);
                        break;
                }
            }
        }, FIRING_RATE);
    }
});

world.afterEvents.itemStopUse.subscribe((event) => {
    const player = event.source;
    const item = event.itemStack;

    const tankTag = Array.from(player.getTags()).find(tag => tag.startsWith('tank_'));
    if (!tankTag) return;

    const tankId = tankTag.split('_')[1];
    const tank = player.dimension.getEntities().find(e => e.id === tankId);
    if (!tank) return;

    const vehicleConfig = Object.values(VEHICLES).find(v => v.identifier === tank.typeId);
    if (!vehicleConfig || (vehicleConfig.modelType !== "IFV_ROCKET" && vehicleConfig.modelType !== "IFV")) return;

    if (item?.typeId === vehicleConfig.mainGunItem) {
        isMainGunFiring = false;
        if (firingInterval) {
            tank.playAnimation("animation.ifv_rocket107.after_fire_main");
            system.clearRun(firingInterval);
            firingInterval = null;
        }
    }
});

system.runInterval(() => {
    const ticked = [];
    for (const dimension of Object.values(dimensions)) {
        const allEntities = dimension.getEntities();
        for (const e of allEntities) {
            if (e.typeId === heatProjectileId) {
                ticked.push(e.id);
                handleHeatHit(e, heatCache[e.id]);
            }
            else if (e.typeId === apfsdsProjectileId) {
                ticked.push(e.id);
                handleApfsdsHit(e, apfsdsCache[e.id]);
            }
            else if (e.typeId === heshProjectileId) {
                ticked.push(e.id);
                handleHeshHit(e, heshCache[e.id]);
            }
        }
    }

    [heatCache, apfsdsCache, heshCache].forEach(cache => {
        for (const id in cache) {
            if (!ticked.includes(id)) {
                delete cache[id];
            }
        }
    });
}, 1);
