import range from "../../modules/arrayRange.js";
import registerSystem from "../../register/registerSystem.js";
import * as mc from "@minecraft/server";
import * as mcui from "@minecraft/server-ui";



class Monitor extends registerSystem {
    constructor() {
        super();
        this.monitor_item = "estr:monitor_pad";
        this.tick(() => {
            this.getPlayers().forEach(player => {
                let handItem = this.getHandItem(player);
                let facing = (option) => {
                    let x = parseFloat(option.position1.x + option.position2.x);
                    let y = parseFloat(option.position1.y - option.position2.y);
                    let rot = parseFloat(option.rotation);
                    return 57.2958 * Math.atan2(y,x) + rot;
                };
                if (player?.hasTag("create.monitor_position")) {
                    let list = handItem?.getLore();
                    let ui = new mcui.MessageFormData();
                    ui.title("监控定位");
                    ui.body("是否选该位置作为监控位置");
                    ui.button2("确定");
                    ui.button1("取消");
                    ui.show(player).then(response => {
                        if (response.selection === 1) {
                            let player_pos = Object.fromEntries("xyz".split("").map(xyz => {
                                return [ xyz, Math.round(player?.location[xyz]) ]
                            }))
                            let block_pos = Object.fromEntries("xyz".split("").map(xyz => {
                                return [ xyz, Math.round(this.getBlockFromViewVector(player)[xyz]) ]
                            }))
                            /*
                            let rot = Object.fromEntries("xy".split("").map(xy => {
                                return [ xy, Math.round(player?.getRotation()[xy]) ]
                            }))
                            */
                            let rot = {
                                x: -player?.getRotation().x.toFixed(2),
                                y: facing({
                                    position1: {
                                        x: player_pos.x,
                                        y: player_pos.z
                                    },
                                    position2: {
                                        x: block_pos.x,
                                        y: block_pos.z
                                    },
                                    rotation: player?.getRotation().y + 180
                                }).toFixed(2)
                            }
                            let data = [
                                ...Object.values(block_pos),
                                ...Object.values(rot)
                            ].join("|");
                            
                            list.push(data);
                            
                            let newItem = new mc.ItemStack(this.monitor_item);
                            newItem?.setLore(list);
                            player?.getComponent("inventory").container.setItem(player?.selectedSlot,newItem)
                            player?.sendMessage({
                                rawtext: [
                                    {
                                        translate: `chat.monitor.create`,
                                        with: [ data ]
                                    }
                                ]
                            })
                        }
                    })
                    player?.removeTag("create.monitor_position")
                }
                if (player?.hasTag("use.monitor_position")) {
                    let list = handItem?.getLore();
                    let ui = new mcui.ActionFormData();
                    ui.title("ui.");
                    ui.body("§r");
                    ui.button("返回");
                    list.forEach(value => {
                        ui.button({
                            translate: "ui.button.text.monitor.check",
                            with: [ value ]
                        })
                    })
                    ui.show(player).then(response => {
                        if (response.selection > 0) {
                            list.forEach((value,index) => {
                                if (response.selection === index + 1) {
                                    let array = value.split("|");
                                    let pos = {
                                        x: parseInt(array[0]),
                                        y: parseInt(array[1]),
                                        z: parseInt(array[2])
                                    }
                                    let rot = {
                                        x: parseFloat(array[3]),
                                        y: parseFloat(array[4])
                                    }
                                    player?.addTag("isWatchMonitor");
                                    this.runCommand(`camera @s set minecraft:free ease 0 linear pos ${Object.values(pos).join(" ")} rot ${Object.values(rot).join(" ")}`, player)
                                }
                            })
                        }
                    })
                    player?.removeTag("use.monitor_position")
                }
                if (player?.hasTag("delete.monitor_position")) {
                    let list = handItem?.getLore();
                    let ui = new mcui.ActionFormData();
                    ui.title("ui.");
                    ui.body("§r");
                    ui.button("返回");
                    list.forEach(value => {
                        ui.button({
                            translate: "ui.button.text.monitor.delete",
                            with: [ value ]
                        })
                    })
                    ui.show(player).then(response => {
                        if (response.selection > 0) {
                            let data = list[response.selection - 1];
                            let newList = list.filter(value => value !== data);
                            let newItem = new mc.ItemStack(this.monitor_item);
                            newItem?.setLore(newList);
                            player?.getComponent("inventory").container.setItem(player?.selectedSlot,newItem)
                            player?.sendMessage({
                                rawtext: [
                                    {
                                        translate: `chat.monitor.delete`,
                                        with: [ data ]
                                    }
                                ]
                            })
                        }
                    })
                    player?.removeTag("delete.monitor_position")
                }
            })
        },1)
        this.listenForEvent("minecraft:itemUseOn",(eventData) => {
            let { block, itemStack, source } = eventData;
            if (!source?.hasTag("isWatchMonitor") && source?.isSneaking && source?.typeId === "minecraft:player" && itemStack?.typeId === this.monitor_item) {
                source?.addTag("create.monitor_position");
            }
        })
        this.listenForEvent("minecraft:itemStartUse",(eventData) => {
            let { itemStack, source } = eventData;
            if (source?.hasTag("isWatchMonitor") && source?.typeId === "minecraft:player" && itemStack?.typeId === this.monitor_item) {
                this.runCommand(`camera @s clear`, source)
                source?.removeTag("isWatchMonitor")
            }
            if (!source?.hasTag("isWatchMonitor") && source?.typeId === "minecraft:player" && itemStack?.typeId === this.monitor_item) {
                let mode = [
                    "use",
                    "delete"
                ]
                source?.addTag(mode[+source?.isSneaking] + ".monitor_position");
            }
        })
    }

}

const system = new Monitor();
