import { EntityComponentTypes, InputPermissionCategory, system, world, } from "@minecraft/server";
import { ActionFormData, ModalFormData } from "@minecraft/server-ui";
import { allMountIDs, spawnSaddleTypes, worldHeightMap } from "../DATA/Config";
import { applyPropertyMapping, createPropertyMapping, SaddleEventMapping } from "./CallingHorn";
import * as Vector3Utils from "../U/Vector3Utils";
import { setFlyProperty } from "./Flying";
const saveModalForm = new ModalFormData().title({
    rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.newfasttraveltitle", with: ["\n"] }],
});
saveModalForm.submitButton("Select Icon");
saveModalForm.textField({
    rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.fasttravelnameinput", with: ["\n"] }],
}, {
    rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.fasttravelnameinputhint", with: ["\n"] }],
});
const colourList = ["§0", "§1", "§2", "§3", "§4", "§5", "§6", "§9", "§a", "§b", "§c", "§d", "§e", "§f"];
saveModalForm.dropdown({
    rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.fasttravelcolorinput", with: ["\n"] }],
}, [
    {
        rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.color_black", with: ["\n"] }],
    },
    {
        rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.color_darkblue", with: ["\n"] }],
    },
    {
        rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.color_darkgreen", with: ["\n"] }],
    },
    {
        rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.color_darkaqua", with: ["\n"] }],
    },
    {
        rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.color_darkred", with: ["\n"] }],
    },
    {
        rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.color_darkpurple", with: ["\n"] }],
    },
    {
        rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.color_gold", with: ["\n"] }],
    },
    {
        rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.color_blue", with: ["\n"] }],
    },
    {
        rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.color_green", with: ["\n"] }],
    },
    {
        rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.color_aqua", with: ["\n"] }],
    },
    {
        rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.color_red", with: ["\n"] }],
    },
    {
        rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.color_lightpurple", with: ["\n"] }],
    },
    {
        rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.color_yellow", with: ["\n"] }],
    },
    {
        rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.color_white", with: ["\n"] }],
    },
]);
saveModalForm.submitButton;
async function addFastTravelLocation(player) {
    let fastTravelCount = player.getDynamicProperty("kicu_mmad:fastTravelCount") ?? 0;
    let locationName = "";
    await saveModalForm
        .show(player)
        .then((formData) => {
        if (formData?.formValues) {
            locationName = (colourList[formData.formValues[1]] + formData.formValues[0]);
            fastTravelCount++;
        }
    })
        .catch((error) => {
        return -1;
    });
    if (!validateLocationName(player, locationName))
        return;
    let fastTravelIconId = await openIconSelectionMenu(player);
    player.setDynamicProperty("kicu_mmad:fastTravelLocationName" + fastTravelCount, locationName);
    player.setDynamicProperty("kicu_mmad:fastTravelLocation" + fastTravelCount, player.location);
    player.setDynamicProperty("kicu_mmad:fastTravelDimension" + fastTravelCount, player.dimension.id);
    player.setDynamicProperty("kicu_mmad:fastTravelCount", fastTravelCount);
    player.setDynamicProperty("kicu_mmad:fastTravelIconId" + fastTravelCount, fastTravelIconId);
}
function validateLocationName(player, locationName) {
    if (locationName.length === 2 || locationName === "" || locationName === undefined) {
        player.sendMessage({
            rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.nameempty", with: ["\n"] }],
        });
        return false;
    }
    let fastTravelCount = player.getDynamicProperty("kicu_mmad:fastTravelCount") ?? 0;
    for (let i = 1; i <= fastTravelCount; i++) {
        if (locationName === player.getDynamicProperty("kicu_mmad:fastTravelLocationName" + i)) {
            player.sendMessage({
                rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.nameexists", with: ["\n"] }],
            });
            return false;
        }
    }
    return true;
}
function tryFastTravel(player) {
    if (!player.inputPermissions.isPermissionCategoryEnabled(InputPermissionCategory.Dismount))
        return;
    const modalForm = new ActionFormData().title({
        rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.fasttraveltitle", with: ["\n"] }],
    });
    const fastTravelIds = getFastTravelIds(player);
    fastTravelIds.forEach((id) => {
        modalForm.button(player.getDynamicProperty("kicu_mmad:fastTravelLocationName" + id), `textures/kicu/mmad/misc/fast_travel_icon_${player.getDynamicProperty("kicu_mmad:fastTravelIconId" + id)}`);
    });
    modalForm
        .show(player)
        .then((formData) => {
        if (formData.selection !== undefined) {
            const id = fastTravelIds[formData.selection];
            const location = player.getDynamicProperty("kicu_mmad:fastTravelLocation" + id);
            const dimension = player.getDynamicProperty("kicu_mmad:fastTravelDimension" + id);
            const ridingComponent = player.getComponent(EntityComponentTypes.Riding);
            const mount = ridingComponent?.entityRidingOn;
            if (allMountIDs.includes(mount?.typeId)) {
                initiateFastTravel(mount, player, location, world.getDimension(dimension));
            }
        }
    })
        .catch((error) => {
        return -1;
    });
}
async function openIconSelectionMenu(player) {
    const spellBladeSelectionMenu = new ActionFormData().title({
        rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.newfasttraveltitle", with: ["\n"] }],
    });
    for (let i = 1; i <= 12; i++) {
        spellBladeSelectionMenu.button({
            rawtext: [{ translate: "dialog.kicu_mmad:fast_travel.fasttravel_icon_" + i, with: ["\n"] }],
        }, `textures/kicu/mmad/misc/fast_travel_icon_${i}`);
    }
    let selection = 1;
    await spellBladeSelectionMenu.show(player).then((response) => {
        if (response.selection || response.selection === 0) {
            selection = response.selection + 1;
        }
    });
    return selection;
}
function initiateFastTravel(mount, player, location, dimension) {
    const mountViewDirectionNormalizedHorizontal = Vector3Utils.normalizeHorizontal(mount.getViewDirection());
    const takeOffVelocity = Vector3Utils.multiply(Vector3Utils.normalize({
        x: mountViewDirectionNormalizedHorizontal.x,
        y: 2,
        z: mountViewDirectionNormalizedHorizontal.z,
    }), 0.4);
    const takeOffRotation = mount.getRotation();
    setFlyProperty(mount, 2);
    player.setDynamicProperty("kicu_mmad:teleportComplete", false);
    const dimensionHeightLimit = worldHeightMap[mount.dimension.id];
    let x = 0;
    player.inputPermissions.setPermissionCategory(InputPermissionCategory.Dismount, false);
    const intevalId = system.runInterval(() => {
        mount.clearVelocity();
        const mountTeleportLocation = Vector3Utils.add(mount.location, takeOffVelocity);
        const teleportBlock = mount.dimension.getBlock(mountTeleportLocation);
        setFlyProperty(mount, 2);
        if (mountTeleportLocation.y > dimensionHeightLimit ||
            teleportBlock?.isAir ||
            teleportBlock?.isLiquid ||
            teleportBlock?.permutation.matches("tallgrass") ||
            teleportBlock?.permutation.matches("double_plant") ||
            teleportBlock?.permutation.matches("yellow_flower") ||
            teleportBlock?.permutation.matches("red_flower") ||
            teleportBlock?.permutation.matches("snow_layer")) {
            mount.teleport(mountTeleportLocation, { rotation: takeOffRotation });
            x++;
            if (x >= 148)
                system.clearRun(intevalId);
        }
    }, 1);
    system.runTimeout(() => {
        player.camera.fade({ fadeTime: { fadeInTime: 2, holdTime: 5, fadeOutTime: 2 } });
    }, 100);
    system.runTimeout(() => {
        handleMountTeleportaion(mount, player, location, dimension);
    }, 150);
    system.runTimeout(() => {
        setFlyProperty(mount, 1);
        player.setDynamicProperty("kicu_mmad:teleportComplete", true);
        player.inputPermissions.setPermissionCategory(InputPermissionCategory.Dismount, true);
    }, 230);
}
function handleMountTeleportaion(mount, player, location, dimension) {
    const propertyMapping = createPropertyMapping(mount);
    mount.remove();
    const dimensionHeightLimit = worldHeightMap[dimension.id];
    system.runTimeout(() => {
        player.teleport({ x: location.x, y: dimensionHeightLimit, z: location.z }, { dimension: dimension });
    }, 1);
    let newMount;
    const intervalId = system.runInterval(() => {
        let areaLoaded = false;
        areaLoaded =
            dimension.runCommand(`testforblock ${location.x} ${dimensionHeightLimit} ${location.z} air`).successCount > 0;
        if (areaLoaded) {
            newMount = dimension.spawnEntity(mount.typeId, {
                x: location.x,
                y: location.y + 15,
                z: location.z,
            });
            applyPropertyMapping(newMount, propertyMapping);
            const mountSaddle = propertyMapping["saddle"];
            const mountSaddleType = propertyMapping["saddle_type"];
            newMount.triggerEvent(SaddleEventMapping.getEvent(mountSaddle, mountSaddleType));
            newMount.triggerEvent(`kicu_mmad:set_saddle_type_${spawnSaddleTypes[mountSaddleType]}`);
            const intervalId3 = system.runInterval(() => {
                const addRiderComponent = newMount.getComponent(EntityComponentTypes.Rideable);
                if (addRiderComponent.getRiders().length === 0) {
                    addRiderComponent.addRider(player);
                }
                else {
                    setFlyProperty(newMount, 1);
                }
                if (player.getDynamicProperty("kicu_mmad:teleportComplete")) {
                    system.clearRun(intervalId3);
                }
            }, 1);
            system.clearRun(intervalId);
        }
    }, 1);
    const intervalId2 = system.runInterval(() => {
        try {
            if (!player.isValid())
                return;
            if (newMount.isValid())
                newMount.clearVelocity();
            if (player.getDynamicProperty("kicu_mmad:teleportComplete")) {
                system.runTimeout(() => {
                    setFlyProperty(mount, 0);
                }, 60);
                system.clearRun(intervalId2);
            }
        }
        catch (e) { }
    }, 1);
}
function getFastTravelIds(player) {
    let ids = [];
    player.getDynamicPropertyIds().forEach((id) => {
        if (id.startsWith("kicu_mmad:fastTravelLocationName")) {
            id = id.replace("kicu_mmad:fastTravelLocationName", "");
            ids.push(parseInt(id));
        }
    });
    return ids.sort();
}
export function fastTravel(player) {
    const ridingComponent = player.getComponent(EntityComponentTypes.Riding);
    const mount = ridingComponent?.entityRidingOn;
    if (allMountIDs.includes(mount?.typeId)) {
        tryFastTravel(player);
    }
    else {
        addFastTravelLocation(player);
    }
}

//# sourceMappingURL=../../../../../_KiCuMountsBPDebug/kicu/mmad/C/FastTravel.js.map
