#pragma region License
/*
License (OLC-3)
~~~~~~~~~~~~~~~

Copyright 2018 - 2023 OneLoneCoder.com

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions or derivations of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

2. Redistributions or derivative works in binary form must reproduce the above
copyright notice. This list of conditions and the following	disclaimer must be
reproduced in the documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors may
be used to endorse or promote products derived from this software without specific
prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS	"AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT	HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL,	SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT	(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
#pragma endregion
#pragma once
#include "Item.h"
#include <stack>
#include "safemap.h"
#include "Theme.h"
#include "Attributable.h"
#include "olcUTIL_Geometry2D.h"

class Crawler;
class MenuComponent;
class ScrollableWindowComponent;

enum MenuType{
    TEST,
    TEST_2,
    INVENTORY,
    CLASS_INFO,
    CLASS_SELECTION,
    MAIN_MENU,
    OVERWORLD_LEVEL_SELECT,
    ITEM_LOADOUT,
    LEVEL_COMPLETE,
    ///////////////////////////////////////////////////////////
    /*DO NOT REMOVE!!*/ENUM_END////////////////////////////////
    ///////////////////////////////////////////////////////////
};

class Menu:public IAttributable{
    friend class Crawler;
    friend struct Player;
    friend class ItemInfo;

    float buttonHoldTime=0;
    vi2d selection={-1,-1};
    vi2d lastActiveMousePos={};

    MenuComponent*draggingComponent=nullptr;
    Renderable r,overlay;
    static safemap<ITCategory,std::vector<MenuComponent*>>inventoryListeners; //All menu components that care about inventory updates subscribe to this list indirectly (See Menu::AddInventoryListener()).
public:
    //The constructor is private. Use CreateMenu() instead!
    Menu()=default;
    ~Menu();
    void AddComponent(std::string key,MenuComponent*button);
    void Update(Crawler*game);
    void Draw(Crawler*game);
    static void InitializeMenus();
    static void OpenMenu(MenuType menu,bool cover=true);
    static void CloseMenu();
    static void CloseAllMenus();
    static void CleanupAllMenus();
    static std::vector<Menu*>stack;
    static std::string themeSelection;
    static safeunorderedmap<std::string,Theme>themes;
    static std::vector<MenuComponent*>unhandledComponents; //This list contains MenuComponents that are created and haven't been assigned via AddComponent. If we get to the end of menu initialization and there are any components in this vector, we have leaked memory and will report this.
    static const vf2d CENTERED;
    static bool IsMenuOpen();
    safemap<std::string,MenuComponent*>components; //A friendly way to interrogate any component we are interested in.
    std::vector<MenuComponent*>displayComponents; //Components that are only for displaying purposes.
    static std::map<MenuType,Menu*>menus;
    vf2d pos; //Specify the upper-left corner of the window. Using CENTERED will always put this where the upper-left corner would center the window.
    vf2d size; //Size in tiles (24x24), every menu will be tile-based
    safemap<int/*Y*/,std::vector<MenuComponent*>>buttons; //Buttons are stored in rows followed by their column order.
    safemap<int/*Y*/,std::vector<MenuComponent*>>keyboardButtons; //Button ordered storage for keyboard/menu 

    static Theme&GetCurrentTheme();
    bool UsingMouseNavigation();
    void SetMouseNavigation(bool mouseNavigation);
    static void InventorySlotsUpdated(ITCategory cat); //Called whenever an inventory item gets added to the player's inventory, thus increasing the total number of slots in our bag.
    static void AddInventoryListener(MenuComponent*component,ITCategory category); //Adds a component to be in a given listener category.
    vf2d center();
    //Returns the last menu type created and last registered component, in case a component is detected as memory leaking, provides this information to each component for safety.
    static std::pair<MenuType,std::string>GetMemoryLeakReportInfo();
    virtual void Cleanup();

    static void DrawThemedWindow(vf2d menuPos,vf2d size,Pixel renderColor=WHITE);

    //X (0-2), Y (0-2) for specific 9-patch tile (tiled version).
    static Renderable&GetPatchPart(int x,int y);
private:
    Menu(vf2d pos,vf2d size);
    static MenuType lastMenuTypeCreated;
    static std::string lastRegisteredComponent;
    void HoverMenuSelect(Crawler*game);
    void MenuSelect(Crawler*game);
    void CheckClickAndPerformMenuSelect(Crawler*game);
    //Mandatory before any menu operations! This creates and sets up the menu in memory.
    static Menu*CreateMenu(MenuType type,vf2d pos,vf2d size);
    
    static void InitializeTestMenu();
    static void InitializeTestSubMenu();
    static void InitializeConsumableInventoryWindow();
    static void InitializeClassInfoWindow();
    static void InitializeClassSelectionWindow();
    static void InitializeMainMenuWindow();
    static void InitializeOverworldMapLevelWindow();
    static void InitializeItemLoadoutWindow();
    static void InitializeLevelCompleteWindow();

    void KeyboardButtonNavigation(Crawler*game,vf2d menuPos);
    static void DrawScaledWindowBackground(Crawler*game,vf2d menuPos,vf2d size,Pixel renderColor);
    static void DrawTiledWindowBackground(Crawler*game,vf2d menuPos,vf2d size,Pixel renderColor);
    static void DrawScaledWindowBorder(Crawler*game,vf2d menuPos,vf2d size,Pixel renderColor);
    static void DrawTiledWindowBorder(Crawler*game,vf2d menuPos,vf2d size,Pixel renderColor);

    //This triggers if we use a keyboard/controller input to try and select some off-screen menu item. We should ideally follow the menu cursor.
    bool HandleOutsideDisabledButtonSelection(MenuComponent*disabledButton);

    Pixel GetRenderColor();
    static bool MOUSE_NAVIGATION;
    static bool cover; //A black cover for when a menu pops up to fade out the stuff behind it.
};

template<typename T>
T*Component(MenuType menu,std::string componentName){
    return (T*)Menu::menus[menu]->components[componentName];
}

struct MenuFuncData{
    Menu&menu;
    Crawler*game;
    MenuComponent*component;
    ScrollableWindowComponent*parentComponent;
};

typedef std::function<bool(MenuFuncData)> MenuFunc;