import * as NativeUI from '../libs/NativeUI';

const UIMenu = NativeUI.Menu;
const UIMenuItem = NativeUI.UIMenuItem;
const UIMenuListItem = NativeUI.UIMenuListItem;
const UIMenuCheckboxItem = NativeUI.UIMenuCheckboxItem;
const BadgeStyle = NativeUI.BadgeStyle;
const Point = NativeUI.Point;
const ItemsCollection = NativeUI.ItemsCollection;
const Color = NativeUI.Color;

export default function itemShopList(globalData: GlobalData) {


    const localPlayer = mp.players.local;
    var playerPos;
    var myVar;

    let mainMenu = null;
    let items = [];
    let currentMenuIdx = -1;
    let menuTransition = false; // workaround for ItemSelect event being called twice between menu transitions



    function addItems(data) {

        // Fill it

        for (const item of data) {
            
            const tempItem = new UIMenuItem(item.Name, "");

            tempItem.SetRightLabel(`${item.Price > 0 ? `$${item.Price}` : "FREE"}`);

            mainMenu.AddItem(tempItem);

            items.push(item);
        }

 
    }

   
   
    function myTimer() {
        let dist = mp.game.gameplay.getDistanceBetweenCoords(localPlayer.position.x, localPlayer.position.y, 0, playerPos.x, playerPos.y, 0, false);
        if (dist > 3) {
            clearInterval(myVar);
            if (mainMenu && mainMenu.Visible) mainMenu.Close();
        }
    }

    mp.events.add("itemMenu:updateData", (jsonData) => {
        if (!globalData.InMenu) {
            globalData.InMenu = true;
            playerPos = localPlayer.position;
            var data = JSON.parse(jsonData);

            // Default menu banner

            const bannerSprite = {
                library: "shopui_title_conveniencestore",
                texture: "shopui_title_conveniencestore"
            };

            // Hide the chat
            mp.gui.chat.show(false);

            // Reset some variables
            currentMenuIdx = -1;
            menuTransition = false;


            // Create a new main menu
            mainMenu = new UIMenu("", "CHOOSE A ITEM", new Point(0, 0), bannerSprite.library, bannerSprite.texture);
            mainMenu.Visible = true;

            // Add items
            addItems(data);

            myVar = setInterval(myTimer, 100);

            // Main menu events
            mainMenu.ItemSelect.on((selectedItem, itemIndex) => {
                const nextItem = items[itemIndex];
                mp.events.callRemote("SERVER:BuyItems", nextItem.Name);

            });

            mainMenu.MenuClose.on(() => {
                globalData.InMenu = false;
                mp.gui.chat.show(true);

                currentMenuIdx = -1;
            });
        }
    });

    mp.events.add("itemMenu:close", () => {
        if (mainMenu && mainMenu.Visible) mainMenu.Close();
    });

    mp.events.add("itemMenu:Error", () => {
        mp.game.audio.playSoundFrontend(1, "Hack_Failed", "DLC_HEIST_BIOLAB_PREP_HACKING_SOUNDS", true);
    });
}