-- ============================================================
-- DBZ Union — customização runtime do OTClient
-- ============================================================

local DBZUNION_HOST = '194.163.133.132'  -- domínio oficial
local DBZUNION_PORT = '7171'
local DBZUNION_VERSION = '860'

local MUSIC_FILE = '/sounds/dbz_gt_theme.ogg'
local MUSIC_VOLUME = 0.25

local musicChannel

local HIDE_IDS = {
  'topLeftOnlinePlayers', 'topLeftDiscord', 'topLeftYoutube', 'panelPingFps',
  'fpsLabel', 'pingLabel', 'lblfps', 'lblping',
  'topLeftOnlinePlayersLabel', 'topLeftDiscordStreamersLabel',
  'topLeftYoutubeStreamersLabel', 'topLeftYoutubeViewersLabel',
  'discordIcon', 'youtubeIcon',
  'clientVersionLabel',
  'serverLabel', 'serverHostTextEdit', 'serverListButton',
  'clientLabel', 'clientComboBox',
  'portLabel', 'serverPortTextEdit',
  'autoLoginBox', 'httpLoginBox',
  'serverInfoLabel',
  'bottomMenu',
}

local function hideById(id)
  if not rootWidget then return false end
  local w = rootWidget:recursiveGetChildById(id)
  if w then
    w:setVisible(false)
    pcall(function() w:setHeight(0); w:setOn(false) end)
    return true
  end
  return false
end

local function forceServerSettings()
  -- Forca os settings (storage)
  g_settings.set('host', DBZUNION_HOST)
  g_settings.set('port', DBZUNION_PORT)
  g_settings.set('client-version', DBZUNION_VERSION)
  g_settings.set('httpLogin', false)

  -- IMPORTANTE: quando user clica Entrar, o cliente lê o TEXTO dos widgets, não o g_settings.
  -- Por isso precisa popular os widgets também, mesmo escondidos.
  if rootWidget then
    local hostEdit = rootWidget:recursiveGetChildById('serverHostTextEdit')
    if hostEdit then
      hostEdit:setText(DBZUNION_HOST)
      print('[DBZ Union] hostEdit setado: ' .. (hostEdit:getText() or 'nil'))
    end
    local portEdit = rootWidget:recursiveGetChildById('serverPortTextEdit')
    if portEdit then
      portEdit:setText(DBZUNION_PORT)
    end
    -- Tenta popular o clientComboBox de varias formas
    local clientCombo = rootWidget:recursiveGetChildById('clientComboBox')
    if clientCombo then
      pcall(function()
        clientCombo:setCurrentOptionByData(tonumber(DBZUNION_VERSION))
      end)
      pcall(function()
        clientCombo:setText(DBZUNION_VERSION)
      end)
    end
    -- httpLoginBox tem que estar UNCHECKED
    local httpBox = rootWidget:recursiveGetChildById('httpLoginBox')
    if httpBox then
      pcall(function() httpBox:setChecked(false) end)
    end
    -- "Remember password" marcado por default (pra salvar credenciais)
    local rememberBox = rootWidget:recursiveGetChildById('rememberEmailBox')
    if rememberBox then
      pcall(function() rememberBox:setChecked(true) end)
    end
  end
end

local function applyHidesAndSettings()
  local hidden = 0
  for _, id in ipairs(HIDE_IDS) do
    if hideById(id) then hidden = hidden + 1 end
  end
  forceServerSettings()
  print(string.format('[DBZ Union] %d widgets escondidos, host=%s', hidden, DBZUNION_HOST))
end

-- IDs dos painéis laterais vazios que ocupam espaço (gameLeftPanel/Extra e gameRightExtraPanel)
-- Mantemos gameMainRightPanel e gameRightPanel (têm minimap, inventário, skills).
local EMPTY_SIDE_PANELS = {
  'gameLeftPanel', 'gameLeftExtraPanel', 'gameRightExtraPanel',
}

local function hideEmptySidePanels()
  if not rootWidget then return end
  local hidden = 0
  for _, id in ipairs(EMPTY_SIDE_PANELS) do
    local w = rootWidget:recursiveGetChildById(id)
    if w then
      pcall(function()
        w:setOn(false)        -- dispara o style $!on (width 0, visible false)
        w:setVisible(false)
        w:setWidth(0)
      end)
      hidden = hidden + 1
    end
  end
  -- Esconde também os botões de seleção de coluna laterais (as setinhas)
  for _, id in ipairs({'gameSelectLeftColumn', 'gameSelectRightExtraColumn'}) do
    local w = rootWidget:recursiveGetChildById(id)
    if w then pcall(function() w:setVisible(false) end) end
  end
  if hidden > 0 then print(string.format('[DBZ Union] %d painéis laterais vazios escondidos', hidden)) end
end

local function playTheme()
  if musicChannel then return end
  local ok, err = pcall(function()
    -- Só toca se o arquivo existir
    if g_resources and g_resources.fileExists and not g_resources.fileExists(MUSIC_FILE) then
      print('[DBZ Union] Sem arquivo de musica custom: ' .. MUSIC_FILE)
      return
    end
    if g_sounds.preload then g_sounds.preload(MUSIC_FILE) end
    musicChannel = g_sounds.getChannel(SoundChannels.Music)
    if musicChannel then
      musicChannel:setGain(MUSIC_VOLUME)
      musicChannel:enqueue(MUSIC_FILE, 0)
    end
  end)
  if not ok then print('[DBZ Union] Erro musica: ' .. tostring(err)) end
end

-- Para TODA musica (custom + default ambient) ao entrar no jogo
local function stopAllMusic()
  pcall(function()
    if musicChannel then musicChannel:stop(); musicChannel = nil end
  end)
  -- Mata todos os canais conhecidos do OTClient
  local channels = {'Music', 'Ambient', 'Effect', 'Master'}
  for _, name in ipairs(channels) do
    pcall(function()
      local ch = SoundChannels and SoundChannels[name]
      if ch and g_sounds and g_sounds.getChannel then
        local c = g_sounds.getChannel(ch)
        if c then
          c:stop()
          c:setEnabled(false)
        end
      end
    end)
  end
  -- Tambem desabilita o sistema de som inteiro (failsafe)
  pcall(function()
    if g_sounds.setAudioEnabled then g_sounds.setAudioEnabled(false) end
  end)
  print('[DBZ Union] Musica parada (entrou no jogo)')
end

-- Reativa audio ao deslogar (efeitos in-game podem precisar)
local function resumeAudio()
  pcall(function()
    if g_sounds.setAudioEnabled then g_sounds.setAudioEnabled(true) end
  end)
end

-- Conecta no evento de login do jogo pra esconder painéis laterais e parar a musica
local function onGameStart()
  -- Para musica IMEDIATAMENTE (e algumas vezes pra garantir)
  stopAllMusic()
  scheduleEvent(stopAllMusic, 200)
  scheduleEvent(stopAllMusic, 1000)

  -- Esconde painel lateral vazios
  scheduleEvent(hideEmptySidePanels, 100)
  scheduleEvent(hideEmptySidePanels, 500)
  scheduleEvent(hideEmptySidePanels, 1500)
  scheduleEvent(hideEmptySidePanels, 3000)
end

-- Quando deslogar, reativa audio (pra musica de login tocar de novo se quiser)
local function onGameEnd()
  resumeAudio()
end

function init()
  print('[DBZ Union] Mod inicializado, host=' .. DBZUNION_HOST)
  forceServerSettings()
  scheduleEvent(applyHidesAndSettings, 100)
  scheduleEvent(applyHidesAndSettings, 500)
  scheduleEvent(applyHidesAndSettings, 1500)
  scheduleEvent(applyHidesAndSettings, 4000)
  scheduleEvent(playTheme, 1500)

  -- Conecta hooks de inicio e fim de jogo
  if g_game then
    connect(g_game, { onGameStart = onGameStart, onGameEnd = onGameEnd })
    -- Caso o cliente ja esteja in-game (reload do mod): aplica direto
    if g_game.isOnline and g_game.isOnline() then
      onGameStart()
    end
  end
end

function terminate()
  if g_game then
    pcall(function() disconnect(g_game, { onGameStart = onGameStart, onGameEnd = onGameEnd }) end)
  end
  if musicChannel then
    pcall(function() musicChannel:stop() end)
    musicChannel = nil
  end
end
