import {world, system, Player} from "@minecraft/server";
import { debug, Check, getCooldownTime, clamp, healthParticle, toColor } from "../mathAndCalculations.js";
import {findBlocks} from '../utils.js';
import { ModalFormData } from "@minecraft/server-ui";

system.afterEvents.scriptEventReceive.subscribe((event) => {
    const { id, message, sourceEntity: player } = event;
	const bell = findBlocks('minecraft:bell', player.dimension, player.location, 4);
	if (id == 'iron_golem:generated' && bell) {
		player.dimension.setBlockType(player.location, 'sw:stone_waystone');
	}
	if (id == 'se:config') {
		configForm(player);
	}
	// For air swinging
    if (id !== "se:attack") return;
	if (world.getDynamicProperty("addon_toggle") == false) return;
    const status = player.getStatus();
    const { equippableComp, item, stats } = player.getItemStats();
    
    if (!(player instanceof Player)) return;
    
    if (player.__leftClick == true) {
        player.__leftClick = false;
        return;
    }
    
    if (player.__rightClick == true) {
        player.__rightClick = false;
        status.shieldDelay = 0;
        return;
    }
    
    if (Check.block(player) && !Check.view(player)) return;
    
    status.lastAttackTime = Date.now();
    
    debug(`${Math.random().toFixed(2)} attack event by ${player.name}`);
});

// Config form
function configForm(player) {
	const status = player.getStatus();
	const op = player.isOp() || player.hasTag("sweepnslash.config");
	let formValuesPush = 0;
	
    let form = new ModalFormData()
    .title({ translate:"sweepnslash.configmenutitle" })
    
    function dp(object, { id, value } = {}) {
	    if (value !== undefined) object.setDynamicProperty(id, value);
	    return object.getDynamicProperty(id);
	}
	
	if (op == true) {
	    if (!world.isHardcore) form.toggle({ translate: "sweepnslash.toggleaddon" }, dp(world, { id: "addon_toggle" }));
		form.toggle({ translate: "sweepnslash.shieldbreakspecial" }, dp(world, { id: "shieldBreakSpecial" }));
	    form.toggle({ translate: "sweepnslash.toggledebugmode" }, dp(world, { id: "debug_mode" }));
	}
	
	form.toggle({ translate: "sweepnslash.excludepetfromsweep" }, dp(player, { id: "excludePetFromSweep" }) ?? false);
	form.dropdown(
	    { translate: "sweepnslash.indicatorstyle" },
	    [{ translate: "sweepnslash.crosshair" }, { translate: "sweepnslash.hotbar" }, { translate: "sweepnslash.geyser" }, { translate: "sweepnslash.none" }],
	    dp(player, { id: "cooldownStyle" })
	);
	form.toggle({ translate: "sweepnslash.bowhitsound" }, dp(player, { id: "bowHitSound" }) ?? false);
	form.toggle({ translate: "sweepnslash.sweepparticles" }, dp(player, { id: "sweep" }) ?? false);
	form.toggle({ translate: "sweepnslash.enchantedhitparticles" }, dp(player, { id: "enchantedHit" }) ?? false);
	form.toggle({ translate: "sweepnslash.damageindicatorparticles" }, dp(player, { id: "damageIndicator" }) ?? false);
	form.toggle({ translate: "sweepnslash.critparticles" }, dp(player, { id: "criticalHit" }) ?? false);
	form.toggle({ translate: "sweepnslash.critsounds" }, dp(player, { id: "critSound" }) ?? false);
	
	form.textField(
	    { rawtext: [{ text: "\n" }, { translate: "sweepnslash.sweepRGBtitle" }, { text: "\n\n" }, { text: "R" }] },
	    "0~255",
	    JSON.stringify(dp(player, { id: "sweepR" }) ?? 255)
	);
	form.textField("G", "0~255", JSON.stringify(dp(player, { id: "sweepG" }) ?? 255));
	form.textField("B", "0~255", JSON.stringify(dp(player, { id: "sweepB" }) ?? 255));
    
    form.submitButton({ translate:"sweepnslash.saveconfig" });
    
    form.show(player).then((response) => {
        const { canceled, formValues, cancelationReason } = response;
        
        function n(value) {
        	const num = Number(value);
	        if (isNaN(value)) player.sendMessage({ translate:"sweepnslash.nan" })
	        return isNaN(num) ? 0 : num
        }
        
        if (response && canceled && cancelationReason === "UserBusy") {
            configForm(player);
            return;
        }
        if (canceled) {
        	player.sendMessage({ translate:"sweepnslash.canceled" });
	        return;
        } else if (!canceled) {
        	player.sendMessage({ translate:"sweepnslash.saved" });
        }

		function valuePush(object, dynamicProperty, push, isRgb) {
		    if (push) {
		        const value = isRgb ? clamp(n(formValues[formValuesPush]), 0, 255) : formValues[formValuesPush];
		        object.setDynamicProperty(dynamicProperty, value);
		        formValuesPush++;
		    }
		}
		
		const properties = [
		    { object: world, dynamicProperty: "addon_toggle", push: op && !world.isHardcore },
			{ object: world, dynamicProperty: "shieldBreakSpecial", push: op },
		    { object: world, dynamicProperty: "debug_mode", push: op },
		    { object: player, dynamicProperty: "excludePetFromSweep", push: true },
		    { object: player, dynamicProperty: "cooldownStyle", push: true },
			{ object: player, dynamicProperty: "bowHitSound", push: true },
		    { object: player, dynamicProperty: "sweep", push: true },
		    { object: player, dynamicProperty: "enchantedHit", push: true },
		    { object: player, dynamicProperty: "damageIndicator", push: true },
		    { object: player, dynamicProperty: "criticalHit", push: true },
		    { object: player, dynamicProperty: "critSound", push: true },
		    { object: player, dynamicProperty: "sweepR", push: true, isRgb: true },
		    { object: player, dynamicProperty: "sweepG", push: true, isRgb: true },
		    { object: player, dynamicProperty: "sweepB", push: true, isRgb: true },
		];
		
		properties.forEach(({ object, dynamicProperty, push, isRgb }) => {
		    valuePush(object, dynamicProperty, push, isRgb);
		});
        
    })
}
