#include "ui/ui_helpers.lua"
#include "ui/ui_extensions.lua"


controllerDisconnectedShow = false
controllerDisconnectedWasPaused = false
controllerDisconnectedAlpha = 0
controllerDisconnectedMessage = 
    IsRunningOnXbox() and "loc@UI_TEXT_GAMEPAD_DISABLED_CONNECT_GAMEPAD_XBOX" 
    or "loc@UI_TEXT_GAMEPAD_DISABLED_CONNECT_GAMEPAD"


function init()
end


function tick()
    if (IsRunningOnXbox() or IsRunningOnPlaystation()) and not controllerDisconnectedShow and LastInputDevice() == UI_DEVICE_GAMEPAD and not HasInputController() then
        controllerDisconnectedShow = true
        controllerDisconnectedWasPaused = GetBool("game.paused")
        SetValue("controllerDisconnectedAlpha", 1, "easeout", 0.25)
        SetPaused(true)
    end
    if controllerDisconnectedShow then
        if not controllerDisconnectedWasPaused then
            SetBool("hud.disablepausemenu", true)
        end
        SetBool("game.disablepause", true)
        SetBool("game.disablemap", true)
    end
end


function draw()
    drawControllerDisconnected()
end


function drawControllerDisconnected()
    if controllerDisconnectedAlpha == 0 then
        return
    end
    UiMute(controllerDisconnectedAlpha)
    UiSetCursorState(UI_CURSOR_HIDE_AND_LOCK)
    UiWindow(UiWidth(), UiHeight())
    UiModalBegin(true)
        UiBlur(controllerDisconnectedAlpha)
        UiTranslate(UiCenter(), UiMiddle())
        local rectY = 296
        UiPush()
            UiColorFilter(1, 1, 1, controllerDisconnectedAlpha)
            UiTranslate(0, -0.5 * rectY)
            UiAlign("center")
            local refSize = 54
            local indicationIcon = "ui/common/indication_162x162.png"
            local w,_ = UiGetImageSize(indicationIcon)
            local scale = refSize / w
            UiTranslate(0,38)
            UiPush()
                UiScale(scale,scale)
                UiImage(indicationIcon)
            UiPop()

            local lineSpacing = 30*0.655
            UiTranslate(0, refSize + 50 + 0.5*lineSpacing)
            UiFont("regular.ttf", 30)
            UiTextLineSpacing(lineSpacing)
            UiWordWrap(1000)
            UiTextAlignment("center")
            local _,sy = UiText(controllerDisconnectedMessage)

            UiTranslate(0, sy + 50 + 0.5*lineSpacing)
            UiButtonImageBox("common/box-outline-6.png", 6, 6, 1, 1, 0.5)
            UiTextAlignment("left")
            UiColor(1, 1, 0.5)

            UiNavGroupBegin()
            if UiTextButton("loc@UI_BUTTON_OK", 200, 38) or InputPressed("menu_accept") then
                controllerDisconnectedShow = false
                SetValue("controllerDisconnectedAlpha", 0, "easein", 0.25)
                if not controllerDisconnectedWasPaused then
                    SetPaused(false)
                end
            end
            UiNavGroupEnd()
        UiPop()
    UiModalEnd()
end
