import * as NativeUI from '../../libs/NativeUI';
import maleHair from "./male_hair.json";
import femaleHair from "./female_hair.json";
import main from '../../Jobs/main';

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;
const maxHairColor = 64;

export default function friseurShopList(globalData: IGlobalData) {
    const categoryTitles = {
        clothes: {
            1: "Masks",
            2: "Frisur",
            3: "Torsos",
            4: "Legs",
            5: "Bags and Parachutes",
            6: "Shoes",
            7: "Accessories",
            8: "Undershirts",
            9: "Body Armors",
            10: "Decals",
            11: "Tops"
        },

        props: {
            0: "Hats",
            1: "Glasses",
            2: "Ears",
            6: "Watches",
            7: "Bracelets"
        }
    };

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

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

    function getClothingName(key, ClotheId, gender) {
        var textures = []

        var hair;

        if (!gender) {
            hair = maleHair;
        } else {
            hair = femaleHair;
        }

        switch (key) {
          case 2:
                for (var i = 0; i < Object.keys(hair[ClotheId]).length; i++) {
                    if (hair[ClotheId][i].Localized != "NULL") {
                        const newData = {
                            id: i,
                            data: [hair[ClotheId][i]]
                        }
                        textures.push(newData);
                    }
                }
                break;
             
        }
        return textures;
    }

    function addClothingItems(type, bannerSprite, key, value, gender) {
        var categoryMenu;
        var cloth = [];
        var tx = [];

        if (Object.keys(categoryMenus).length > 0) {
            for (var i = 0; i < categoryMenus.length; i++) {
                if (categoryMenus[i].slotIdx == key) {
                    return;
                }
            }
            mainMenu.AddItem(new UIMenuItem(categoryTitles[type][key]));
            // Create category menu
            categoryMenu = new UIMenu("", categoryTitles[type][key].toUpperCase(), new Point(0, 0), bannerSprite.library, bannerSprite.texture);
            categoryMenu.Visible = false;
        } else {
            mainMenu.AddItem(new UIMenuItem(categoryTitles[type][key]));
            // Create category menu
            categoryMenu = new UIMenu("", categoryTitles[type][key].toUpperCase(), new Point(0, 0), bannerSprite.library, bannerSprite.texture);
            categoryMenu.Visible = false;
        }

        


        mainMenu.Item

        // Fill it

        for (const item of value) {
            if (item.ComponentId == key) {
                var txData = getClothingName(key, item.ClotheId, gender);

                for (const x of txData) {
                    //var itemDescription = (key === 11 ? mp.game.ui.getLabelText(x.undershirt[1].GXT) : "Clothing item.");
                    var itemDescription = (key === 11 ? x.undershirt[1].GXT + " - " + x.id : "Clothing item.");
                    if (itemDescription == "NULL") {
                        itemDescription = "Clothing item.";
                    }
                    const tempItem = new UIMenuItem(mp.game.ui.getLabelText(x.data[0].GXT));
                    //const tempItem = new UIMenuItem(x.data[0].GXT + " - " + x.id, itemDescription);

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

                    categoryMenu.AddItem(tempItem);

                    cloth.push(item);
                    tx.push(x);
                }
            }
        }

        categoryMenus.push({
            menu: categoryMenu,
            type: type,
            slotIdx: Number(key),
            item: cloth,
            texture: tx
        });
    }

    function submenuItemChangeHandler(newIndex) {
        const currentMenu = categoryMenus[currentMenuIdx];
        const currentItem = currentMenu.item[newIndex];
        const currentTexture = currentMenu.texture[newIndex].id;
        //const currentItem = clothingData[currentMenu.type][currentMenu.slotIdx][newIndex];

         
        mp.players.local.setComponentVariation(currentMenu.slotIdx, currentItem.ClotheId, currentTexture, 2);
        

        /*
        case "props":
            if (currentItem.drawable === -1) {
                localPlayer.clearProp(currentMenu.slotIdx);
            } else {
                localPlayer.setPropIndex(currentMenu.slotIdx, currentItem.drawable, currentItem.texture, true);
            }
            break;
        */
    }

    function resetPreview() {
        if (lastClothing) {
            switch (lastClothing.type) {
                case "clothes":
                        localPlayer.setComponentVariation(lastClothing.slotIdx, lastClothing.drawable, lastClothing.texture, 2);
                    
                    break;

                case "props":
                    if (lastClothing.drawable === -1) {
                        localPlayer.clearProp(lastClothing.slotIdx);
                    } else {
                        localPlayer.setPropIndex(lastClothing.slotIdx, lastClothing.drawable, lastClothing.texture, true);
                    }
                    break;
            }

            lastClothing = null;
        }
    }

    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);
            resetPreview();
            if (currentMenuIdx !== -1) categoryMenus[currentMenuIdx].menu.Close();
            if (mainMenu && mainMenu.Visible) mainMenu.Close();
        }
    }


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

            // Default menu banner
            if (bannerSprite == null) {
                bannerSprite = {
                    library: "commonmenu",
                    texture: "interaction_bgd"
                };
            } else if (bannerSprite == 10) {
                bannerSprite = {
                    library: "shopui_title_barber",
                    texture: "shopui_title_barber"
                };
            }
            // Hide the chat
            mp.gui.chat.show(false);

            // Reset some variables
            categoryMenus = [];
            currentMenuIdx = -1;
            menuTransition = false;
            lastClothing = null;

            // Create a new main menu
            mainMenu = new UIMenu("", "Wähle deine Frisur", new Point(0, 0), bannerSprite.library, bannerSprite.texture);
            mainMenu.Visible = true;

            // Update clothingData
            clothingData = data;

            // Add clothes

            addClothingItems("clothes", bannerSprite, 2, data[0], gender);
            myVar = setInterval(myTimer, 100);
            // Add props
            // for (const [key, value] of Object.entries(clothingData.props)) addClothingItems("props", bannerSprite, key, value);

            let hairColorItem;
            let hairHighlightItem;
            var creatorHairMenu;
            let hairColors = [];
            for (let i = 0; i < maxHairColor; i++) hairColors.push(i.toString());


            hairColorItem = new UIMenuListItem("Haarfarbe", "Deine Haarfarbe", new ItemsCollection(hairColors));
            mainMenu.AddItem(hairColorItem);
          /*  hairHighlightItem = new UIMenuListItem("Haarstr\u00e4hnen", "Farbe deiner Haarstr\u00e4hnen", new ItemsCollection(hairColors));
            mainMenu.AddItem(hairHighlightItem);
          */ //Wird später hinzugefügt
            mainMenu.ListChange.on((item, listIndex) => {
                switch (mainMenu.CurrentSelection) {
                    case 1: // hair color
                        localPlayer.setHairColor(listIndex, 0);
                        break;

                    /* case 2: // hair highlight color
                        localPlayer.setHairColor(hairColorItem.Index, listIndex);
                        break;
                        */
                }
            });


            // Submenu events
            for (const item of categoryMenus) {
                // Preview hovering item
                item.menu.IndexChange.on(submenuItemChangeHandler);

                // Buy hovering item
                item.menu.ItemSelect.on((item: NativeUI.UIMenuItem, itemIndex) => {
                    if (menuTransition) {
                        menuTransition = false;
                        return;
                    }

                    const currentMenu = categoryMenus[currentMenuIdx];
                    const currentItem = currentMenu.item[itemIndex];
                    const currentTexture = currentMenu.texture[itemIndex].id;

                    var serverData = [currentMenu.slotIdx, currentTexture, currentItem.ClotheId, -1, -1, -1, currentItem.Price];
                    if (lastClothing.drawable == currentItem.ClotheId && lastClothing.texture == currentTexture) {
                        mp.game.audio.playSoundFrontend(1, "Hack_Failed", "DLC_HEIST_BIOLAB_PREP_HACKING_SOUNDS", true);
                    } else {
                        mp.events.callRemote("SERVER:BuyCharacterClothes", "clothe", JSON.stringify(serverData), currentItem.CloteID);
                        mp.events.call("friseurMenu:close");
                    }
                    

                });

                // Reset preview when player backs out of category menu
                item.menu.MenuClose.on(() => {
                    

                    currentMenuIdx = -1;
                    mainMenu.Visible = true;
                    if (mainMenu.Visible = true) {
                        resetPreview();
                    }
                });
            }

            // Main menu events
            mainMenu.ItemSelect.on((selectedItem, itemIndex) => {
                if (selectedItem === hairColorItem) {
                    mp.events.callRemote("SERVER:BuyHairColor", hairColorItem.SelectedValue);
                    mainMenu.Close(true);
                    globalData.InMenu = false;

                }
                else if (selectedItem === hairHighlightItem) {
                    mp.events.callRemote("CLIENT:BuyHairlightColor", hairHighlightItem.SelectedValue);
                    mainMenu.Close(true);
                    globalData.InMenu = false;
                } else {

                const nextMenu = categoryMenus[itemIndex];
                const slot = Number(nextMenu.slotIdx);

                lastClothing = {
                    type: nextMenu.type,
                    slotIdx: slot,
                    drawable: (nextMenu.type === "props" ? localPlayer.getPropIndex(slot) : localPlayer.getDrawableVariation(slot)),
                    texture: (nextMenu.type === "props" ? localPlayer.getPropTextureIndex(slot) : localPlayer.getTextureVariation(slot)),
                    undershirt: [localPlayer.getDrawableVariation(8), localPlayer.getTextureVariation(8)],
                    torso: localPlayer.getDrawableVariation(3)
                };
                

                currentMenuIdx = itemIndex;
                mainMenu.Visible = false;
                nextMenu.menu.Visible = true;
                menuTransition = true;

                    submenuItemChangeHandler(nextMenu.menu.CurrentSelection);
                }
            });


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

                currentMenuIdx = -1;
                lastClothing = null;
            });
        }
    });
    mp.events.add("friseurMenu:close", () => {
        if (currentMenuIdx !== -1) categoryMenus[currentMenuIdx].menu.Close();
        if (mainMenu && mainMenu.Visible) mainMenu.Close();
    });

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