local classlib = require("core.class")
local tablex = require("core.tablex")
local animationUtil = require("ui.animationUtil")
local attributeUtil = require("ui.attributeUtil")
local buttonUtil = require("ui.buttonUtil")
local colors = require("ui.colors")
local consts = require("ui.consts")
local exchangeCard = require("ui.exchangeCard")
local fsm = require("ui.fsm")
local lamsConsts = require("ui.lamsConsts")
local list = require("ui.list")
local menu = require("ui.menu")
local pickupConsts = require("ui.pickupConsts")
local pickupUtil = require("ui.pickupUtil")
local recipeUtil = require("ui.recipeUtil")
local resourceConsts = require("ui.resourceConsts")
local resourceUtil = require("ui.resourceUtil")
local toggle = require("ui.toggle")
local util = require("ui.util")
local AI = game.AI
local Player = game.Player
local UI = game.UI
local ResourcesMenu = classlib.Class("ResourcesMenu", fsm.UIState)
local ResourcesOff = ResourcesMenu:StateClass("ResourcesOff", fsm.UIState)
local ResourcesOn = ResourcesMenu:StateClass("ResourcesOn", fsm.UIState)
local Resource = ResourcesMenu:StateClass("Resource", fsm.UIState)
local StoryItem = ResourcesMenu:StateClass("StoryItem", fsm.UIState)
local resourcesMenu = ResourcesMenu.New("resourcesMenu", {
  ResourcesOff,
  ResourcesOn,
  {Resource, StoryItem}
})
function ResourcesMenu:Setup()
  self.pauseMenuOpened = false
end
function ResourcesMenu:Enter()
  self:WantPadEvents(true)
  self:TurnOff()
end
function ResourcesMenu:TurnOff()
  self:Goto("ResourcesOff")
end
function ResourcesMenu:EVT_PAUSE_MENU_OPEN()
  self.pauseMenuOpened = true
end
ResourcesMenu.EVT_GAME_OVER = ResourcesMenu.TurnOff
ResourcesMenu.EVT_Restart = ResourcesMenu.TurnOff
function ResourcesOff:Setup()
  self.resourcesOn = self:GetState("ResourcesOn")
end
function ResourcesOff:Enter()
end
function ResourcesOff:Exit()
end
function ResourcesOff:EVT_TURN_ON_RESOURCES_MENU(instructionEntries, instructionArgs)
  self.resourcesOn.menu:set_instructionEntries(instructionEntries)
  self.resourcesOn.menu:set_instructionArgs(instructionArgs)
  self:Goto("ResourcesOn")
end
function ResourcesOn:Setup()
  self.menu = menu.Menu.New(self, {})
  self.resourcesMenu = self:GetState("resourcesMenu")
  self.showDesc = true
  self.itemComparisonCardOn = false
  local goExchangeCard = util.GetUiObjByName("Resources_exchange_card")
  self.exchangeCard = exchangeCard.ExchangeCard.New(self, goExchangeCard)
  self.exchangeCard:Init()
  if UI.SetUIGORenderLayer ~= nil then
    UI.SetUIGORenderLayer(goExchangeCard, consts.RenderLayer_WorldUI)
  end
  self.menu:SetupSubmenuList(consts.inworldMenu_SubmenuList, nil, nil)
  util.Show("vendorMenuListBlur", "vendorListBackingGrow")
  util.Hide("Resources_Stave_Group")
end
function ResourcesOn:UpdateAccessibilityScaling()
  self.exchangeCard:UpdateAccessibilityScaling()
end
function ResourcesOn:Enter()
  self.menu:Activate()
  self:UpdateAccessibilityScaling()
  self.itemComparisonCardOn = false
  UI.WorldUIRender("cameraJoint")
  util.Show("Resources")
  self.shared.resourceHeaderText = util.GetLAMSMsg(lamsConsts.Resources)
  local submenuList = self.menu:GetList(consts.inworldMenu_SubmenuList)
  if self.resourcesMenu.pauseMenuOpened == true then
    local init_useOnGainFocus = false
    submenuList:SetSelectedButton(1, init_useOnGainFocus)
  end
  local newItemArray = self:SubmenuList_GetItems()
  local showList = true
  local useOnGainFocus = not self.menu:HasInstructionEntryForMenuState()
  local itemDetermineFocusabilityFunc = function(substateName)
    return self:IsSubstateFocusable(substateName)
  end
  local getDisplayNameFunc
  self.menu:RefreshSubmenuList(submenuList, newItemArray, showList, useOnGainFocus, itemDetermineFocusabilityFunc, getDisplayNameFunc)
  animationUtil.MoveWorldUIMainList("ListJoint_Pickups")
  self:SendEventToUIFsm("inWorldMenu", "EVT_CLEAR_ATTRIBUTES_PREVIEW")
  self:SendEventToUIFsm("inWorldMenu", "EVT_HIDE_ATTRIBUTE_CARD")
  self:SendEventToUIFsm("inWorldMenu", "EVT_REFRESH_NOTIFICATIONS")
  self.menu:ExecuteInstructions()
end
function ResourcesOn:Exit()
  self.menu:Deactivate(true)
  self.shared.resourceHeaderText = ""
  self.shared.recipeHeaderText = ""
  util.Hide("Resources", "Resources_Stave_Group")
  self.exchangeCard:HideCard()
end
function ResourcesOn:SubmenuList_GetItems()
  local subStateNames = {}
  for _, substateName in ipairs(consts.SUB_STATES.Resources) do
    tablex.FastInsert(subStateNames, substateName, #subStateNames + 1)
  end
  return subStateNames
end
function ResourcesOn:IsSubstateFocusable(substateName)
  local isFocusable = false
  local isSonState = substateName == "SonRecipes"
  if not isSonState or isSonState and not util.SonUI_ShouldDisable() then
    isFocusable = true
  end
  return isFocusable
end
function ResourcesOn:SubmenuList_Button_Update(button)
  local alphaValue = 1
  local fadeTime = 0
  button:AlphaFade(alphaValue, fadeTime)
  button:SetIcon(button:get_item())
  button:UpdateNewIcon(nil)
end
function ResourcesOn:SubmenuList_Button_OnGainFocus(button)
  local currentItem = button:get_item()
  local labelText = ""
  self.menu:SetSubmenuListLabelText(consts.inworldMenu_SubmenuList, labelText)
  local subState = self:GetState(currentItem)
  subState.menu:set_instructionEntries(self.menu:get_instructionEntries())
  animationUtil.UpdateCamera(self, pickupConsts.TAG_PICKUP_KRATOS, "Resources")
  self:Goto(currentItem)
end
function ResourcesOn:SelectResource(currState, resourceName)
  local showAll = false
  local character
  if resourceName ~= nil then
    self.exchangeCard:ShowCard(showAll)
    self.exchangeCard:SetItem(resourceName, resourceConsts.RESOURCE_FLAG_RESOURCE)
  else
    self.exchangeCard:HideCard(showAll)
  end
  self:SendEventToUIFsm("inWorldMenu", "EVT_HIDE_ATTRIBUTE_CARD")
  self:UpdateFooterButtonPrompt(currState.menu)
end
function ResourcesOn:Button_OnGainFocus(currState, button)
  local currItem = button:get_item()
  self:SelectResource(currState, currItem)
end
function ResourcesOn:Button_OnLoseFocusResource(button)
  local resourceName = button:get_item()
  if resourceName ~= nil then
    resourceUtil.ClearNew(resourceName)
    button:UpdateNewIcon(function(button)
      return buttonUtil.ShowNotification(button, consts.NotificationTypes.Resource)
    end)
  end
end
function ResourcesOn:Button_OnLoseFocusRecipe(button)
  local recipeName = button:get_item()
  if recipeName ~= nil then
    recipeUtil.ClearNew(recipeName)
    button:UpdateNewIcon(function(button)
      return buttonUtil.ShowNotification(button, consts.NotificationTypes.Recipe)
    end)
  end
end
function ResourcesOn:Button_OnLoseFocus(currState, button)
  if currState.viewingResources == true then
    self:Button_OnLoseFocusResource(button)
  else
    self:Button_OnLoseFocusRecipe(button)
  end
end
function ResourcesOn:Button_UpdateResource(button)
  local resourceName = button:get_item()
  if resourceName == nil then
    buttonUtil.UpdateColorQuad(button, colors.WHITE)
  else
    local rarityColor = resourceUtil.GetRarityColor(resourceName)
    if resourceUtil.GetRarity(resourceName) == nil then
      rarityColor = nil
    end
    local amount = resourceUtil.GetAmount(resourceName)
    local textColorStyle = 0 < amount and "Color_White" or "Color_Gray50"
    local alphaValue = 1
    local fadeTime = 0
    button:AlphaFade(alphaValue, fadeTime)
    button:SetTextColor(colors.WHITE)
    button:SetText("text", util.StyleText(button:get_text(), textColorStyle))
    button:SetText("text_rightAligned", util.StyleText(tostring(amount), textColorStyle))
    buttonUtil.UpdateColorQuad(button, rarityColor)
    button:UpdateNewIcon(nil)
    button:UpdateEquippedIcon(nil)
  end
end
function ResourcesOn:Button_Update(currState, button)
  self:Button_UpdateResource(button)
end
function ResourcesOn:UpdateFooterButtonPrompt(currMenu)
  local showTouchPadMap = game.IsMapAvailable() and game.build.GOLD_VERSION ~= 0
  currMenu:UpdateFooterButton("Map", showTouchPadMap)
  currMenu:UpdateFooterButton("Weapon", true)
  currMenu:UpdateFooterButton("Skill", true)
  currMenu:UpdateFooterButton("Quest", true)
  currMenu:UpdateFooterButton("Settings", true)
  currMenu:UpdateFooterButton("Exit", true)
  currMenu:UpdateFooterButton("Close", true)
  currMenu:UpdateFooterButtonText()
end
function ResourcesOn:SubmenuSetup(currState)
  currState.menu = menu.Menu.New(currState, {
    FooterButtonInfo = {
      {
        Item = "Map",
        Text = "[TouchPad] " .. util.GetLAMSMsg(lamsConsts.Map),
        EventHandlers = {
          {
            Events = {
              "EVT_TouchPad_Release"
            },
            Handler = function()
              self:SendEventToUIFsm("globalMenu", "EVT_GO_TO_MAP")
            end
          }
        }
      },
      {
        Item = "Weapon",
        Text = "",
        EventHandlers = {
          {
            Events = {
              "EVT_GO_TO_WEAPON_MENU"
            },
            Handler = function()
              self:SendEventToUIFsm("globalMenu", "EVT_GO_TO_WEAPON")
            end
          }
        }
      },
      {
        Item = "Skill",
        Text = "",
        EventHandlers = {
          {
            Events = {
              "EVT_GO_TO_SKILL_TREE_MENU"
            },
            Handler = function()
              self:SendEventToUIFsm("globalMenu", "EVT_GO_TO_SKILL_TREE")
            end
          }
        }
      },
      {
        Item = "Quest",
        Text = "",
        EventHandlers = {
          {
            Events = {
              "EVT_GO_TO_QUEST_MENU"
            },
            Handler = function()
              self:SendEventToUIFsm("globalMenu", "EVT_GO_TO_QUEST")
            end
          }
        }
      },
      {
        Item = "Settings",
        Text = "[TriangleButton] " .. util.GetLAMSMsg(lamsConsts.Options),
        EventHandlers = {
          {
            Events = {
              "EVT_Triangle_Release"
            },
            Handler = function()
              self:SendEventToUIFsm("globalMenu", "EVT_OPEN_SETTINGS_MENU")
            end
          }
        }
      },
      {
        Item = "Exit",
        Text = "[BackButton] " .. util.GetLAMSMsg(lamsConsts.Exit),
        EventHandlers = {
          {
            Events = {
              "EVT_Back_Release"
            },
            Handler = function()
              self:SendEventToUIFsm("globalMenu", "EVT_TURN_OFF_GLOBAL_MENU")
            end
          }
        }
      },
      {
        Item = "Close",
        Text = "",
        EventHandlers = {
          {
            Events = {
              "EVT_Options_Release"
            },
            Handler = function()
              self:SendEventToUIFsm("globalMenu", "EVT_TURN_OFF_GLOBAL_MENU")
            end
          }
        }
      }
    }
  })
  local itemList = list.List.New(currState, {
    MaxFocusableObjectCount = 10,
    ListObjectName = "PickupList",
    EmptyTextLamsID = lamsConsts.NoResourcesAvailable,
    HoverToSelect = true,
    Button_Update = function(button)
      self:Button_Update(currState, button)
    end,
    Button_OnGainFocus = function(button)
      self:Button_OnGainFocus(currState, button)
    end,
    Button_OnLoseFocus = function(button)
      self:Button_OnLoseFocus(currState, button)
    end
  })
  currState.menu:SetList("item", itemList)
end
function ResourcesOn:SubmenuEnter(currState, includeTypes, excludeTypes)
  currState.menu:Activate()
  assert(currState.currCharacter ~= nil, "No character was defined for submenu: " .. tostring(currState.name) .. ". Assign one to pickupConsts.TAG_PICKUP_KRATOS or TAG_PICKUP_SON in the setup function.")
  self.currentCharacter = currState.currCharacter
  tablex.FastInsert(excludeTypes, resourceConsts.RESOURCE_FLAG_ECONOMY, #excludeTypes + 1)
  local itemList = currState.menu:GetList("item")
  if self.resourcesMenu.pauseMenuOpened == true then
    local init_useOnGainFocus = false
    itemList:SetSelectedButton(1, init_useOnGainFocus)
    self.resourcesMenu.pauseMenuOpened = false
  end
  local newItemArray = resourceUtil.GetResources(resourceConsts.WALLET_KRATOS, includeTypes, excludeTypes)
  local showList = true
  local useOnGainFocus = true
  local itemDetermineFocusabilityFunc
  local itemGetTextFunc = resourceUtil.GetDisplayName
  itemList:Refresh(newItemArray, showList, useOnGainFocus, itemDetermineFocusabilityFunc, itemGetTextFunc)
  local submenuList = self.menu:GetList(consts.inworldMenu_SubmenuList)
  local headerText = util.GetLAMSMsg(lamsConsts[submenuList:GetSelectedItem()])
  itemList:SetHeaderText(headerText)
  self:UpdateFooterButtonPrompt(currState.menu)
  currState.menu:ExecuteInstructions()
  if #newItemArray <= 0 then
    self.exchangeCard:HideCard()
  end
end
function ResourcesOn:SubmenuExit(currState)
  if not currState.viewingResources then
    local creature = pickupUtil.GetCreatureFromCharacter(currState.currCharacter)
    local pickupInSlot = pickupUtil.GetPickupNameInSlot(creature, currState.currPickupSlot)
    local pickupStage = pickupUtil.GetStage(pickupInSlot, creature)
    pickupUtil.UpdateSlotOnUICreature(currState.currPickupSlot, pickupInSlot, pickupStage, creature, currState.currCharacter)
  end
  currState.menu:Deactivate(true)
end
function ResourcesOn:EVT_TURN_OFF_RESOURCES_MENU()
  self:Goto("ResourcesOff")
end
function Resource:Setup()
  self.resourcesOn = self:GetState("ResourcesOn")
  self.resourcesOn:SubmenuSetup(self)
  self.viewingResources = true
  self.currCharacter = pickupConsts.TAG_PICKUP_KRATOS
end
function Resource:Enter()
  self.resourcesOn:SubmenuEnter(self, {
    resourceConsts.RESOURCE_FLAG_RESOURCE
  }, {
    resourceConsts.RESOURCE_FLAG_STORY_ITEM
  })
end
function Resource:Exit()
  local buttonList = self.menu:GetList("item"):GetButtons()
  for i = 1, #buttonList do
    buttonList[i]:SetText("text_rightAligned", "")
  end
  self.resourcesOn:SubmenuExit(self)
end
function StoryItem:Setup()
  self.resourcesOn = self:GetState("ResourcesOn")
  self.resourcesOn:SubmenuSetup(self)
  self.viewingResources = true
  self.currCharacter = pickupConsts.TAG_PICKUP_KRATOS
end
function StoryItem:Enter()
  self.resourcesOn:SubmenuEnter(self, {
    resourceConsts.RESOURCE_FLAG_STORY_ITEM
  }, {})
end
function StoryItem:Exit()
  local buttonList = self.menu:GetList("item"):GetButtons()
  for i = 1, #buttonList do
    buttonList[i]:SetText("text_rightAligned", "")
  end
  self.resourcesOn:SubmenuExit(self)
end
function ResourcesMenu:OnSaveCheckpoint(tab)
end
function ResourcesMenu:OnRestoreCheckpoint(tab)
end
