
local ProfileList = nil
local Edit = nil
local Settings = nil
local SettingName = "ProfilesList"

local ForbiddenChatacters = { ";", ":","\"","/","\\","'",".",">","<","|","{","}","?" ," ","!","[","]"}

function OnCreate()
  ProfileList = List( self:FindChild("profile_list") )
  Edit = self:FindChild("profile_edit")
  Settings = Game:GetSettings()  
end

function OnHide()
  Widget("menu_top"):SetVisible(true)  
  s.sys_menu_profile=0
  
  local resources = { "ProfileButtonDown", "ProfileButtonUp","ProfileListLine", "ProfileListBg",
    "ProfilesList", "ProfileVScrollTrack", "ProfileVScroll", "ProfilesBg", "Profiles_UpSpace",
    "Profiles_UpBtn", "Profiles_DownSpcae", "ProfilesEditClient", "ProfilesEdit" }
  for _,v in pairs(resources) do 
    UI:UnloadResource(v)
  end
  UI:DelWidget(self:GetName())
  SetInterfaceCaption("")
end


function OnShow()
  UpdateList( Settings:GetParameter(SettingName) )
  Widget("menu_top"):SetVisible(false)  
  s.sys_menu_profile=1
end

function OnDelProfile(_sender)
  local profiles = DeserializeProfiles()
  local toRemove = ProfileList:GetSelectedItem()
  
  if toRemove == "" then
    return
  end
  print(toRemove, tostring(states["sys_current_profile"]) , toRemove == tostring(states["sys_current_profile"]) )
  local question
  if toRemove ~=  tostring(states["sys_current_profile"]) then
    question =  "#{sys_question_remove_profile} ".." "..toRemove.." #{sys_question_mark}"
  else
    question ="#{sys_question_remove_current_profile}"
  end
  
  MessageBox( L10n:ExpandLine(question),
    function()  
      for i=1,#profiles do 
        if profiles[i] == toRemove then
          if profiles[i] ==  tostring(states["sys_current_profile"]) then SetProfile("") end
          profiles[i] = ""
          SaveMgr:RemoveSubDir(toRemove)
          break
        end
      end  
      
      profiles = SerializeProfiles(profiles)
      
      Settings:SetParameter(SettingName, profiles)  
      Settings:Save()
      print(toRemove ,s.sys_current_profile, toRemove == tostring( s.sys_current_profile))
      if toRemove ==  tostring(s.sys_current_profile) then
        SetProfile("") end
      
      UpdateList()
  end , nil )
end

function OnCancel()
  self:SetVisible(false)
  Widgets.MainMenu.self:SetVisible(true)
end

function OnAddProfile(_sender)
  local profilesTab =  DeserializeProfiles()
  local profiles = Settings:GetParameter(SettingName)
  newprofile = ""
  newprofile = Edit:GetCaption()
  
  if newprofile == "" then
    return
  end
  
  if string.len(newprofile) > 8 then
      MessageBox(L10n:ExpandString("sys_profile_to_long"), nil, nil, {false, false, true})
      return
  end
  
  for i = 1,#ForbiddenChatacters do 
    for l=1,string.len(newprofile) do
      if string.sub( newprofile, l, l ) ==  ForbiddenChatacters[i] then 
          MessageBox(L10n:ExpandString("sys_forbidden_characters"), nil, nil, {false, false, true})
          Edit:SetText("")
          return
      end 
    end
  end
  
  for i=1,#profilesTab do
    if string.upper(profilesTab[i]) ==  string.upper(newprofile) then
      MessageBox(L10n:ExpandString("sys_profile_exists"), nil, nil, {false, false, true})
      return
    end
  end
  
  if profiles:len() > 0 then
    profiles = profiles..","
  end
  
  profiles=profiles..newprofile
  
  profiles = SerializeProfiles(profiles:split(","))
  
  if profiles == "" then
    return
  end
  
  Settings:SetParameter(SettingName, profiles)
  Settings:Save()
  
  Edit:SetText("")
  UpdateList(profiles)
end

function SerializeProfiles(profilesTab)
  profiles = ""
  for i=1,#profilesTab do
    if profilesTab[i] ~= "" then
      if profiles:len() > 0 then
        profiles = profiles..","
      end
  
      profiles = profiles..profilesTab[i]
    end
  end  
  
  return profiles
end

function DeserializeProfiles()
  local profiles = Settings:GetParameter(SettingName)
  return profiles:split(",")
end

function OnChooseProfile(_sender)
  
  -- todo : select profile
  local profile = ProfileList:GetSelectedItem()
  if profile ~= "" then 
    SetProfile(profile)
    self:SetVisible(false)
    Widgets.MainMenu.self:SetVisible(true)
    if SaveMgr:GetSlotsCount() > 0 then
      s.sys_game_start = 0
      scene_nodes.s00_0000_menu.OnGameResume()
      --Widgets.MainMenu.btnBack()
    else
      --Widgets.MainMenu.btnNewGame()
      scene_nodes.s00_0000_menu.OnNewGame()
    end
  end
  
end

function UpdateList(list)
  if list == nil then
    list = Settings:GetParameter(SettingName)
  end
  listTab = list:split(",")
  ProfileList:RemoveAll()
  for i=1,#listTab do
    ProfileList:AddItem(listTab[i])
  end
end

function btnMouseLeave(_sender) 
  --SetInterfaceCaption()
  self:FindChild("profile_caption"):SetText( "")
end

function btnMouseEnter(_sender)
  self:FindChild("profile_caption"):SetText( _sender:GetCaption())
  --SetInterfaceCaption(_sender:GetCaption())
end
  
function EditTextChanged()
  PlaySound("ui_profile_type_letter")
end
