import * as mc from "@minecraft/server";
import * as mcui from "@minecraft/server-ui";
import * as GMath from "./utils/GMath";
import { itemComponents } from "./utils/Components";
//Functions
/**
 * 
 * @param {mc.Container} container 
 * @param {mc.ContainerSlot[]} inventory
 */
function InventorySorter(container, inventory, mode) {
    const sorted = [...inventory].sort((a, b) => {
        if (!a.hasItem() && b.hasItem()) return 1;
        if (a.hasItem() && !b.hasItem()) return -1;
        if (a.hasItem() && b.hasItem()) {
            const aName = a.typeId.split(":", 2)[1]
            const bName = b.typeId.split(":", 2)[1]
            switch (mode) {
                case "name":
                    return aName.localeCompare(bName);
                case "name_reverse":
                    return bName.localeCompare(aName);
                case "amount":
                    return b.amount - a.amount;
                case "amount_reverse":
                    return a.amount - b.amount;
                default:
                    return 0;
            }
        }
    });
    const items = sorted.map((slot) => {
        if (slot.getItem()) {
            return slot.getItem().clone()
        } else {
            return undefined
        }
    })
    sorted.forEach((slot, index) => {
        container.setItem(index, items[index])
    })

}
//Components
class CameraTablet{
    /**
     * @param {mc.ItemComponentUseEvent} ev
     */
    onUse(ev){
        const item = ev.itemStack
        const player = ev.source
        const inCamera = player.getDynamicProperty("camera_id")
        const camerasOwned = player.dimension.getEntities({type: "vtng_rt:camera"}).filter((e)=>e.getDynamicProperty("owner") == player.id)
        if(camerasOwned.length > 0 && inCamera == ""){
            const camerasId = camerasOwned.map(e=> {return e.id;})
            const camerasName = camerasOwned.map(e=> {return e.getDynamicProperty("name");})
            const ui = new mcui.ModalFormData()
            ui.submitButton({rawtext:[{translate:"vtng_rt.camera_select.ui"}]})
            ui.title({rawtext:[{translate: "vtng_rt.camera_tablet_title.ui"}]})
            ui.dropdown({rawtext:[{translate:"vtng_rt.cameras.ui"}]}, camerasName)
            ui.show(player).then((form)=>{
                if(form.canceled == false){
                    const cameraSelected = camerasId[form.formValues[0]]
                    player.setDynamicProperty("camera_id", cameraSelected)
                    player.setDynamicProperty("in_camera", true)
                }
            })
        }
    }
}
class ContainerWand{
    /**
     * @param {mc.ItemComponentUseOnEvent} ev
     */
    onUseOn(ev){
        const block = ev.block
        const player = ev.source
        const container = block.getComponent("inventory")?.container
        const options = [
            "name",
            "name_reverse",
            "amount",
            "amount_reverse"
        ]
        const ui = new mcui.ActionFormData()
        ui.title({ rawtext: [{ translate: "vtng_rt.container_sorter_title.ui" }] })
        ui.button({ rawtext: [{ translate: "vtng_rt.alphabetical_order.ui" }] })
        ui.button({ rawtext: [{ translate: "vtng_rt.decreasing_alphabetical_order.ui" }] })
        ui.button({ rawtext: [{ translate: "vtng_rt.quantity_order.ui" }] })
        ui.button({ rawtext: [{ translate: "vtng_rt.decreasing_quantity_order.ui" }] })
        if(container){
            ui.show(player).then(form => {
                if (form.canceled == false) {
                    const option = options[form.selection]
                    player.dimension.playSound("random.orb", player.location, {volume: 0.6})
                    const slots = []
                    Array(container.size).fill("i").map((_, i) => {
                        const slot = container.getSlot(i)
                        if (slot) {
                            slot.slotIndex = i
                            if (slot.hasItem()) {
                                slot.name = slot.typeId.split(":", 2)[1]
                            }
                            slots.push(slot)
                        }
                    })
                    InventorySorter(container, slots, option)
                    player.sendMessage({rawtext:[{translate:"vtng_rt.container_sorted.warn"}]})
                }
            })
        }else{
            player.sendMessage({rawtext:[{translate:"vtng_rt.invalid_container_sorted.warn"}]})
            player.dimension.playSound("note.bassattack", player.location, {volume: 0.6})
        }
        
    }
}
//Register
itemComponents["vtng_rt:camera_tablet"] = new CameraTablet()
itemComponents["vtng_rt:container_sorter_wand"] = new ContainerWand()