import { getLevel, sendMessage } from "./index";
import { MapApi, MapItemSavedData } from "../index";
import { GameType, InputMode, Player, ServerPlayer, SimulatedPlayer } from "bdsx/bds/player";
import { CommandPermissionLevel, CommandRawText } from "bdsx/bds/command";
import { command } from "bdsx/command";
import { int32_t } from "bdsx/nativetype";
import { ItemStack } from "bdsx/bds/inventory";
import { ProcHacker } from "bdsx/prochacker";
import { UNDNAME_NAME_ONLY } from "bdsx/dbghelp";
import { Actor, ActorDamageSource, ActorUniqueID } from "bdsx/bds/actor";
import { pdb } from "bdsx/core";
import { Vec3 } from "bdsx/bds/blockpos";
import { Level } from "bdsx/bds/level";
import { CompoundTag } from "bdsx/bds/nbt";
import { bedrockServer } from "bdsx/launcher";
import { events } from "bdsx/event";
import { MinecraftPacketIds } from "bdsx/bds/packetids";
import { CANCEL, returnTrue } from "bdsx/common";
import { Form } from "bdsx/bds/form";

const Jimp = require('jimp');
const gis = require('g-i-s');
const followRedirect = require('follow-redirect-url');
const fs = require("fs");
const path = require("path");

const procHacker = ProcHacker.load(path.join(__dirname, '../pdb.ini'), [
    "Level::getLevelStorage",
    "Level::_createMapSavedData",
    "MapItemSavedData::setPixel",
    "MapItemSavedData::setLocked",
    "MapItemSavedData::getParentMapId",
    "MapItemSavedData::save",
    "Actor::getUniqueID"
], UNDNAME_NAME_ONLY);

pdb.setOptions(0);
const procHackerDec = ProcHacker.load(path.join(__dirname, '../pdb.ini'), [
    "?getMapId@MapItem@@SA?AUActorUniqueID@@PEBVCompoundTag@@@Z"
]);
pdb.close();

function searchImages(searchTerm) {
    return new Promise((resolve, reject) => {
      gis(searchTerm, (error, results) => {
        if (error) {
          reject(error);
        } else {
          resolve(results);
        }
      });
    });
  }

events.packetSend(MinecraftPacketIds.Text).on((pkt) => {
    const name = pkt.params.get(0);
    if (pkt.message === "§e%multiplayer.player.joined") {
        if(pkt.params.get(0).startsWith("temp") || pkt.params.get(0).startsWith("temp(")){
            return CANCEL;
        }
        pkt.message = `[ §a+§r ] §7${name}`;
        return;
    }
    if (pkt.message === "§e%multiplayer.player.left") {
        pkt.message = `[ §c-§r ] §7${name}`;
        return;
    }
});

const mapcmd = command.register("map", "Map command", CommandPermissionLevel.Normal)
mapcmd.overload(async (p, o, op) =>{
    const actor = o.getEntity();
    if(actor === null){
        return;
    }
    const player = o.getEntity() as ServerPlayer;
    const ni = actor.getNetworkIdentifier();

    const SelectRequest = Form.sendTo(ni,{
        "type":"form",
        "title":"Выбор загрузки",
        "content":"Запрос/URL",
        "buttons":[
            {
                "text":"Запрос",
                "image":{
                    "type":"url",
                    "data":"https://www.iconpacks.net/icons/2/free-search-icon-3076-thumb.png"
                }
            },
            {
                "text":"URL",
                "image":{
                    "type":"url",
                    "data":"https://static.thenounproject.com/png/2391755-200.png"
                }
            }
        ]
    }).then(async value=>{
        if (value === 0){
            const searchimagebyrequest = await Form.sendTo(ni,{
            "type":"custom_form",
            "title":"Введите запрос",
            "content":[
                {
                "type":"input",
                "text":"Введи запрос",
                "placeholder":"вводить сюда",
                "default":undefined
                },
                {
                "type":"step_slider",
                "text":"Высота",
                "steps":[
                    "1",
                    "2",
                    "3"
                ]
                },
                {
                "type":"step_slider",
                "text":"Ширина",
                "steps":[
                    "1",
                    "2",
                    "3"
                ]
                },
                {
                "type":"slider",
                "text":"номер изображения",
                "min":0,
                "max":100,
                "default":0
                },
                {
                "type":"toggle",
                "text":"Случайное изображение",
                "default":false
                }
            ]
            });
            if(searchimagebyrequest=== null){
                return;
            }
            else if(searchimagebyrequest[0]=== null){
                return player.sendMessage("§l§cВведи запрос");
            }
            else{


                const test = await searchImages(searchimagebyrequest[0]) as any;
                console.log(test)
                const url = JSON.stringify(test[0].url)
                MapApi.setmapimagea(player,url,searchimagebyrequest[1],searchimagebyrequest[2]);

            }
        }
    });
}, {});