---------------------------------------------------------------------------------------------------------------------------------
-- Inventory.lua - inventory script
--  ivnentory panel (gui),  inventory object (logic)
--
--  self  - inventory Widget 
-- Inventory - active inventory object
---------------------------------------------------------------------------------------------------------------------------------

local slots = { }
local slotsCount = 11
local Frame

local ImageSet = "SmallItemsSet"
local ImageGroup = "Items"

local Blocked = false
local SlotClickBlocked = false

Shift = 0
local BigPanel = nil

function ItemOffset(item)
    local ret = {x = 10, y = 10 }
    if  item == "i_duster" then
       ret.x = -23
       ret.y = -15
    end
    return ret    
end

function DefaultImageSet() return  "SmallItemsSet",  "Items" end

function SetImageSet(set, grp)
  ImageSet = set
  ImageGroup = grp
end

function ResetImageSet(set, grp)
  ImageSet, ImageGroup  = DefaultImageSet()
end

function SetSlotImage(slot, name, imageSet, imageGroup)
  if imageSet == nil then 
    imageSet, imageGroup  = DefaultImageSet()
  end
  if slots[slot] ~= nil then
    if name ~= "" and name ~= nil then
      slots[slot]:SetImage( name, imageSet, imageGroup )
    else
      slots[slot]:SetImage( "", "" )
    end
  end
end

-- Inventory callback
function Validate(afterReset)

  if afterReset == true then
    Shift = 0
  end
  
  itemsCount = Inventory:GetItemsCount()
  selectedItem = Inventory:GetSelectedItem()
  if itemsCount > slotsCount then itemsCount = slotsCount end
  
  for i= 0,slotsCount 
  do
    item = Inventory:GetItem( Shift + i + 1)
    if i <= itemsCount and selectedItem ~= item then
      slots[i]:SetImage( item, ImageSet, ImageGroup)
    else
      slots[i]:SetImage("" , "")
    end
  end
end


function SlotClick(_sender)

  if SlotClickBlocked == true then
    return
  end

  item = ItemNameFromSlot(_sender)
  if item_big ~= nil and item_big.IsVisible() and item_big.GetItem() == item then
    return
  end
  
  if Inventory:GetSelectedItem() == "" then
    states.sys_item_under_mouse = ""
    local offset = ItemOffset(item)
   
    Inventory:SelectItem(item, offset.x, offset.y)
  else
    Items.Event( item, Inventory:GetSelectedItem() )
  end
end

function SlotPressed(_sender, _x, _y, _btn)
  if SlotClickBlocked == true then
    return
  end
  
  if _btn == MB_RIGHT and Inventory:GetSelectedItem() == "" then
    local item = ItemNameFromSlot(_sender)
    if item ~= "" and states["sys_block_big_item"] == 0 then
      ShowBigPanel( item )
    end
  end
end


function SlotMouseLeave(sender)
  states.sys_item_under_mouse = ""
end

function SlotMouseEnter(sender)
  states.sys_item_under_mouse = ItemNameFromSlot(sender)
  if states.sys_item_under_mouse == Inventory:GetSelectedItem() then --ItemUnderMouse == Inventory:GetSelectedItem() then
    states.sys_item_under_mouse = ""
  end
end

-- right arrow button click 
function RightArrowClick(_sender)
  if Shift < Inventory:GetItemsCount() - slotsCount - 1 then
    Shift = Shift + 1
    Validate()
  end
end

-- left arrow button click
function LeftArrowClick(_sender)
  if Shift > 0 then 
    Shift = Shift - 1 
    Validate()
  end
end 

function MultiPageItemsMap(item)
    if item == "i_letter" then
        return "i_letter,i_letter_1,i_letter_2,i_letter_3,i_letter_4"
    end
end

function ShowBigPanel(itemName)
    
    if MultiPageItemsMap(itemName) then
        ShowBigPanel(MultiPageItemsMap(itemName))
        return
    end
  -- brzydki hak na znikanie grafik przedmiotow ;]
  if UI:WidgetExists( "item_big") then UI:DelWidget("item_big") end
  UI:AddWidget("item_big.layout")
  BigPanel = Widget("item_big")
  Widgets.item_big.SetItem(itemName)
  BigPanel:SetVisible(true)
end

function HideBigPanel()
  -- brzydki hak na znikanie grafik przedmiotow ;]
  UI:DelWidget("item_big")
end

function ItemNameFromSlot(slot)
  slotNo = tonumber( string.sub( slot:GetName(), 5) )
  return Inventory:GetItem( slotNo + 1 + Shift )
end
----------------------------------------- G U I ------------------------------------------

function Show(s)
  self:SetVisible(s)
end

function OnCreate()
  -- find slots widgets in panel
  for i = 0,slotsCount do
    num = tostring(i)
    if string.len(num) == 1 then num = "0"..num end
    slots[i] = StaticImage( self:FindChild("slot"..num) )
  end  
  Frame = self:FindChild("Frame")
  Lock(true)
end

 -- states
 local Show = 1
 local Hide = 2
 local None = 3
 
 -- invetory show / hide
 local invV = 2 --200 -- speed 
 local InvState = None
 local X = 0
 local time = 0
 local VisibleOffset = 32/116
 
 function StartShow()
  --InvState = Show
 end
 
 function StartHide()
  --InvState = Hide
 end
 
 function MouseEnter(_sender)
  if self:IsVisible() then
    StartShow()
  end
 end
 
 function MouseLeave()
  StartHide()
 end
  
 -- Widget Update 
local Y = 1 - VisibleOffset
function Update(_dt)
    -- show / hide invnetory 
    UpdateAnimations(_dt)
    if not Blocked and InvState ~= None and s.sys_menu_hide==1 then      
      time = time + _dt
      --[[
      if time < 1/invV then
        return
      end
      ]]
      local dS = invV * time
--      local Y = Frame:GetY()
      
      --if dS < 1 then dS = 1 end
      if InvState == Show then
          dS = -dS
      end 
      Y = Y + dS
      if Y <= 0 then
          Y = 0
          posX = 0
          InvState = None
      elseif Y  >= 1 - VisibleOffset then
          Y = 1 - VisibleOffset
          InvState = None
      end
      
      Frame:SetRealPos(X, Y)
      time = 0
    end
end

function Lock(visible)
  if not visible then visible = false end  
  Blocked = true  
  if visible then 
    Y = 0
  else
    Y = 1
  end
  Frame:SetRealPos(X, Y)  
end

function Unlock()
  Blocked = false
  Frame:SetRealPos(X, 0)
  --StartHide()
end

function BlockItemsClick( b )
  SlotClickBlocked = b
end

function MenuButtonClick(_sender)
  if states["sys_block_esc"] == 0 and MystInventory:GetActive():GetSelectedItem() == "" then
    OpenMainMenu()
  end
end

function DiaryButtonClick(_sender)
  if MystInventory:GetActive():GetSelectedItem() ~= "" then return end
  d = OpenDiary()
  d:SetVisible(true)
end


function PulitzerEnter()
  caption = L10n:ExpandString("sys_bonus_name").." "..tostring( states["ho_bonuses_count"] )
  SetInterfaceCaption(caption)
end

function GetSlotMidPos(slot)
  pos   = slots[slot]:GetAbsRelPos()
  size  = slots[slot]:GetAbsRelSize()
  size.y = 0
  return  pos + (size/2)
end

function SetSenderCaption(_sender)
  SetInterfaceCaption(L10n:ExpandString(_sender:GetCaption()))
end

function ResetCaption(_sender)
  SetInterfaceCaption("")
end



function HintClick(_sender)
 -- if CanTakeHintClue() then
	  if  MystInventory:GetActive():GetSelectedItem() ~= "" then return end
      SetHintAnimOnZero()
      
      if PlayHoHint(self:GetName(), _sender:GetName()) then
        return
      end
    
      ShowHint()
  --end
end

 
function SkipMiniGame()
  local BonusesCount = tonumber(states["ho_bonuses_count"])
  if IsSomethingToResolve() and BonusesCount >= 5
  then
    ResolveCurrentMinigame()
    states["ho_bonuses_count"] = BonusesCount - 5
  elseif IsSomethingToResolve() then
    ShowGameHint("game_hint_24")
  end
end 
 
function PostLoad()
  self:FindChild("hint_anim"):SetVisible(false)
  self:FindChild("hint_button"):SetVisible(true)
  
  Widget("diary_btn"):SetVisible(true)
  Widget("diary_anim"):SetVisible(false)
end
 
 action["inventory_after_diary_back"] = function()
  Widget("diary_btn"):SetVisible(true)
  Widget("diary_anim"):SetVisible(false)
 end
 
 function onDiaryLeave()
  --Widget("diary_btn"):SetVisible(true)
  --Widget("diary_anim"):SetVisible(false)
  --AnimateWidgetBack("Inventory", "diary_anim", 0.5, 50, "inventory_after_diary_back")
  
  SetInterfaceCaption("")
  AddToAnimate({
      name        = "diary_anim",
      time        = 0.5/50,
      frame_rate  = 0.5/50, 
      max_frames  = 50,
      back        = true,
      button      = "diary_btn"
    })
end
 
function onDiaryEnter(_sender)
  
  --AnimateWidget("Inventory", "diary_anim", 0.5, 50)
  SetSenderCaption(_sender) 
  
  Widget("diary_btn"):SetVisible(false)
  Widget("diary_anim"):SetVisible(true)  
  StaticImage(self:FindChild("diary_anim")):SetItemIndex(0)

  AddToAnimate({
      name        = "diary_anim",
      time        = 0.5 / 50,
      frame_rate  = 0.5 / 50, 
      max_frames  = 50,
      back        = false,
      button      = "diary_btn"
    })    
end
 
function onDiaryLeaveCaption()
  ResetCaption()
  onDiaryLeave()
end

function FakeMenuBtnEnter(_sender)
  Button("btn_go_menu"):SetMouseFocus(true)
  SetSenderCaption(_sender)
end

function FakeMenuBtnLeave()
  Button("btn_go_menu"):SetMouseFocus(false)
  ResetCaption()
end



local AnimationWidgets = {}
function UpdateAnimations(dt)
  if #AnimationWidgets == 0 then return end
  local toDelete = {}
  local function Stop(n, hide)
    if hide then 
      self:FindChild(AnimationWidgets[n]["button"]):SetVisible(true)
      self:FindChild(AnimationWidgets[n]["name"]):SetVisible(false)
    end
    AnimationWidgets[n]["done"] = true
    table.insert(toDelete, n)    
  end
  
  local maxW = #AnimationWidgets 
  for i=1,maxW do
    if not AnimationWidgets[i]["done"] then
      if AnimationWidgets[i]["time"] > 0 then 
        AnimationWidgets[i]["time"] = AnimationWidgets[i]["time"] - dt
      else
        local anim  = StaticImage(self:FindChild(AnimationWidgets[i]["name"]))
        local frame = anim:GetCurrentIndex()
        
        if AnimationWidgets[i]["back"] 
        then frame = frame - 1
        else frame = frame + 1
        end
        
        if      frame < 0 then Stop(i, true)  return
        elseif  frame > AnimationWidgets[i]["max_frames"] then Stop(i, false) return
        end
        anim:SetItemIndex(frame)
        AnimationWidgets[i]["time"] = AnimationWidgets[i]["frame_rate"]
      end
    end
  end
end


function AddToAnimate(t)
  local maxW = #AnimationWidgets 
  for i=1,maxW do 
    if AnimationWidgets[i]["name"] == t["name"] then
      AnimationWidgets[i]["back"] = t["back"]
      AnimationWidgets[i]["done"] = nil
      return
    end
  end  
  table.insert(AnimationWidgets, t)
end

function GetCounterWidget()
  return self:FindChild("counter")
end
