-- main menu
--------------------------------------------------------------------
function OnHide()
 -- s.sys_menu=0
  s.sys_menu_hide = 1
  SetInterfaceCaption("")  
 --Game:Pause(false)
end

function OnDestroy()
  SetInterfaceCaption("")
end

function OnShow()
  --Game:Pause()
  --s.sys_menu=1
  
  UpdateGreetings()
--[[  
  --Widget("button_save"):SetEnabled( GetSaveButtonVisible() )
  if s.sys_game_start == 1 and s.sys_game_finished == 0 then
    Widget("button_back"):SetEnabled( s.sys_current_profile ~= "" and s.sys_current_profile ~= 0 )
    -- music menu
    if Audio:GetMusic() ~= "menu" then
      s.sys_game_music = Audio:GetMusic()
      SaveMgr:SaveSlot(0)
	  Audio:PauseAllSound()
      PlayMusic("menu",1,0)
    end
  else
    Widget("button_back"):SetEnabled( SaveMgr:GetSlotsCount() > 0 and s.sys_game_finished == 0 and s.sys_current_profile ~= "" and s.sys_current_profile ~= 0)
  end
  OpenTopMenu()
  
  if Widgets.Inventory ~= nil then Widgets.Inventory.HideBigPanel() end
  
  Cursors:Default()
  MystInventory:GetActive():ReleaseItem()
  states["sys_region_under_mouse"] = ""
  ]]
end

function GetSaveButtonVisible()
  ret = true
  ret = ret and ( s.sys_game_start == 1 )
  ret = ret and ( s.hold == 0 )
  ret = ret and ( s.sys_dialog_active == 0 )
  return ret
end

function UpdateGreetings()
  local txt = L10n:ExpandString("sys_welcome").." "
  if states["sys_current_profile"] ~= 0 then txt = txt..states["sys_current_profile"] end
  self:FindChild("text_welcome"):SetText(txt)
  
  self:FindChild("if_not_you_1"):SetVisible( states["sys_current_profile"] ~= 0 and states["sys_current_profile"] ~= "")
  self:FindChild("if_not_you_2"):SetVisible( states["sys_current_profile"] ~= 0 and states["sys_current_profile"] ~= "")
  self:FindChild("if_not_you_3"):SetVisible( states["sys_current_profile"] == 0 or  states["sys_current_profile"] == "")  
end

function OnCreate()
  SetAnimPositions()  
  --s.sys_menu=1  
  UpdateGreetings()  
  --[[
  if s.sys_game_start == 1 and s.sys_game_finished == 0 then
    Widget("button_back"):SetEnabled( s.sys_current_profile ~= "" and s.sys_current_profile ~= 0 )
    --Widget("button_save"):SetEnabled(true)
  else
    Widget("button_back"):SetEnabled(false)
    --Widget("button_save"):SetEnabled(false)
  end
  OpenInventory()
  ]]
end

function OnDestroy()
  --s.sys_menu=0
  s.sys_menu_hide = 1
end

--------------------------------------------------------------------
--button

function RunNewGame()
  if states["sys_current_profile"] == 0 or states["sys_current_profile"] == "" then
    return 
  end
  local profile = states["sys_current_profile"]
  
  if s.sys_ho_active == 1 then
    _G[MystHiddenGroup:GetMainLuaModuleName()].GameStop()
  end
  ResetGame()
  RemoveTasks()
  MystInventory:RemoveAll()
  MystStates:Clear()
  Game:NewGame()
  
  states["sys_current_profile"] = profile  
  
  s.sys_game_start = 1
  states["hero_short_name"] = Config["hero_short_name"]
  
  MystDiary:GetInstance():ClearContent()
	
  OpenInventory()
  OpenTopMenu()
  
  --self:SetVisible(false)
  Widget("MainMenu"):SetVisible(false)
  
  if Config["game_scene_startup"] then 
	GoToProgress(Config["game_scene_startup"])
  else 
	Scene:ChangeCamera("s00_0100_progress")
  end
  
  OnNewGameStart()
end

function btnProfile()
  OpenProfileChooser()
  Widget("MainMenu"):SetVisible(false)
end

function btnNewGame(sender)
  if states["sys_current_profile"] == 0 or states["sys_current_profile"] == "" then
    OpenProfileChooser()
    --self:SetVisible(false)
    Widget("MainMenu"):SetVisible(false)
  else
  --[[
    if s.sys_game_start == 1 then
      MessageBox(L10n:ExpandString("sys_question_unsaved"), RunNewGame )
    else
    ]]
      RunNewGame()
    --end
  end
end

function btnGoSetings(_sender)
  OpenSettingsMenu()
  self:SetVisible(false)
end

function btnGoLoad()
  --OpenLoadMenu()
  if states["sys_current_profile"] == "" then
    MessageBox( L10n:ExpandString("sys_warning_no_profile"), nil, nil, { false, false, true } )
    return
  end
  
  if SaveMgr:LoadSlot(-1) == true then
    self:SetVisible(false)
  else
    MessageBox( L10n:ExpandString("sys_warning_no_save"), nil, nil, { false, false, true } )
  end
end

function btnGoSave()
  --OpenSaveMenu()
  if states["sys_current_profile"] == "" then
    MessageBox(L10n:ExpandString("sys_warning_no_profile"), nil, nil, { false, false, true } )
    return
  end
    
  MessageBox( L10n:ExpandString("sys_rewrite"), 
    function()
      if SaveMgr:SaveSlot(0) == true then
        MessageBox(L10n:ExpandString("sys_game_save"),
          function() self:SetVisible(false) end , 
          nil, 
          { false, false, true } )
      else
        MessageBox( L10n:ExpandString("sys_save_error"), nil, nil) 
      end
    end, nil )
end

function btnGoMovies()
  OpenMoviesMenu()
  self:SetVisible(false)
end

function btnGoCredits()
  OpenCredits()
  self:SetVisible(false)
end

function btnQuit()
  MessageBox( L10n:ExpandString("sys_question_quit"), function()  Game:Exit() end , nil)  
end

function btnBack()
  if s.sys_game_start == 1 then
    s.sys_menu_hide=1
    OpenInventory()
    OpenTopMenu()
	
     -- music menu
    Audio:ResumeAllPausedSound()
    Audio:StopMusic("")
    PlayMusic(s.sys_game_music,1,0)
  else
	ResetGame()
	SaveMgr:LoadSlot(0)
	Audio:PlayMusic("")
  end
  
  s.sys_game_start = 1
  self:SetVisible(false)
end

local Solution = nil
function CloseSolution()
  if Solution == nil then return end
  UI:DelWidget("Solution")
  
  for i=1,12 do 
    UI:UnloadResource("solution_page_"..tostring(i))
  end
  UI:UnloadResource("solution_bg")
  
end

function OnSolutionButton()
  UI:LoadResource("solution.xml")
  UI:LoadResource("solution_pages.xml")
  
  if not UI:WidgetExists("Solution") then
    UI:AddWidget("solution.layout") end
  -- solution
  Solution = Widget("Solution")
  Solution:SetVisible(true)
end

--------------------------------------------------------------------

local AnimationWidgets = {}
--[[
function Update(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
]]
local AnimationFrames = { 
  button_solution = 26, 
  button_profile  = 29,
  button_setings  = 31,
  button_quit     = 29,
  button_new      = 29,
  button_back     = 24
  }

local AnimationTime = { 
  button_profile = 2,
  button_setings = 2,
  button_back     = 1
  }

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 btnMouseEnter(_sender)
  SetInterfaceCaption(L10n:ExpandString(_sender:GetCaption()))
  
  
  if not self:HaveChild(_sender:GetName().."_anim") then return end

  _sender:SetVisible(false)
  self:FindChild(_sender:GetName().."_anim"):SetVisible(true)
  StaticImage(self:FindChild(_sender:GetName().."_anim")):SetItemIndex(0)

  if AnimationTime[_sender:GetName()] == nil then AnimationTime[_sender:GetName()] = 0.5 end 
  AddToAnimate({
      name        = _sender:GetName().."_anim",
      time        = AnimationTime[_sender:GetName()] / AnimationFrames[_sender:GetName()],
      frame_rate  = AnimationTime[_sender:GetName()] / AnimationFrames[_sender:GetName()], 
      max_frames  = AnimationFrames[_sender:GetName()],
      back        = false,
      button      = _sender:GetName()
    })    
end

function btnMouseLeave(_sender)
  SetInterfaceCaption("")
end

function AnimMouseEnter(_sender)
  local name = string.sub(_sender:GetName(), 1, string.len(_sender:GetName()) - 5)
  SetInterfaceCaption(L10n:ExpandString(self:FindChild(name):GetCaption()))
end

function AnimMouseLeave(_sender)
  SetInterfaceCaption("")

  local name = string.sub(_sender:GetName(), 1, string.len(_sender:GetName()) - 5)
  if AnimationTime[name] == nil then AnimationTime[name] = 0.5 end
  AddToAnimate({
      name        = _sender:GetName(),
      time        = AnimationTime[name] / AnimationFrames[name],
      frame_rate  = AnimationTime[name] / AnimationFrames[name], 
      max_frames  = AnimationFrames[name],
      back        = true,
      button      = name
    })
end



function SetAnimPositions()
--[[
  local animations = 
  {
    "button_profile_anim"
    ,"button_new_anim"
    ,"button_quit_anim"
    ,"button_setings_anim"
    ,"button_solution_anim"
    --,"button_back_anim"
  }
  
  local  round =function(num, idp)
    local mult = 10^(idp or 0)
    return math.floor(num * mult + 0.5) / mult
  end
  
  local v = MystViewportManager:GetInstance():GetMainViewport()
  local rts =v:GetRenderTargetSize()
  local r=Widget("MainMenu")
  
  for i=1,#animations do
    local ra = r:FindChild(animations[i])

    local x = ra:GetX() 
    local h = ra:GetHeight() 
    local w = ra:GetWidth() 
    local y = ra:GetY()
    local rect = v:GetRenderRectangle()

    local nx = round( (x/1280) * rect.right*rts.x, 0) 
    local ny = round( (y/720) * (rect.bottom - rect.top)*rts.y, 0) 
    local nw = round( (w/1280) * rect.right*rts.x, 0) 
    local nh = round( (h/720) * (rect.bottom - rect.top)*rts.y, 0) 

    ra:SetPosition(nx, ny)
    ra:SetSize(nw, nh)
  end
]]  
end

