#include "positioning.lua"


function UiGetTouchHitboxMinSize()
	return 45
end


function UiGetDefaultTouchScrollThreshold()
	return 10
end


function UiGetTouchTapMaxMoveDelta()
	return 10
end


function UiGetTouchTapMaxTime()
	return 0.5
end


function UiTouchPressDefaultColorFilter()
	UiColorFilter(1, 1, 1, 1.2)
end


function UiGetTouchLayoutVariant()
	if HasKey("options.input.touch.layout") then
		return GetInt("options.input.touch.layout")
	end
	return 2
end


function UiSetTouchLayoutVariant(variant)
	SetInt("options.input.touch.layout", variant)
end


function UiDrawJoystickTouchControl(sendHorizontalInput, sendVerticalInput)
	local scale = math.max(UiCanvasSize().w / 2360, UiCanvasSize().h / 1640)

	UiPush()
		UiTranslateToScreenLeftEdge(0, 0)
		UiTranslateToScreenBottomEdge(0, 0)
		UiScale(scale)

		-- Joystick background
		local joystickSize = 447.0
		UiTranslate(140, -140 - joystickSize)
		UiColor(1.0, 1.0, 1.0, 1.0)
		UiAlign("left top")
		UiImageBox("ui/hud/touch/joystick_bg.png", joystickSize, joystickSize, 0, 0)

		-- Joystick handle
		local joystickHandleSize = 205.0
		local joystickHandleMaxR = (joystickSize - joystickHandleSize) / 2.0
		local joystickHandleDeadZone = 0.15
		if (sendVerticalInput and not sendHorizontalInput) or (sendHorizontalInput and not sendVerticalInput) then
			joystickHandleDeadZone = 0
		end
		UiTranslate(joystickSize / 2.0, joystickSize / 2.0)
		UiAlign("center middle")
		local joystickTouchId = UiGetScreenTouchIdStartedInCircle(joystickSize / 2.0)
		if joystickTouchId ~= 0 then
			UiTouchPressDefaultColorFilter()
			local x, y = UiGetScreenTouchPos(joystickTouchId)
			local theta = math.atan2(y, x)
			local r = math.clamp(math.sqrt(x * x + y * y), 0, joystickHandleMaxR)
			x = r * math.cos(theta)
			y = r * math.sin(theta)
			UiTranslate(x, y)
			x = x / joystickHandleMaxR
			if math.abs(x) < joystickHandleDeadZone then
				x = 0
			else
				x = (x - joystickHandleDeadZone) / (1 - joystickHandleDeadZone)
			end
			y = y / joystickHandleMaxR
			if math.abs(y) < joystickHandleDeadZone then
				y = 0
			else
				y = (y - joystickHandleDeadZone) / (1 - joystickHandleDeadZone)
			end
			if sendHorizontalInput then
				UiSendInputScreenTouchAction("left", joystickTouchId, math.clamp(-x, 0, 1))
				UiSendInputScreenTouchAction("right", joystickTouchId, math.clamp(x, 0, 1))
			end
			if sendVerticalInput then
				UiSendInputScreenTouchAction("up", joystickTouchId, math.clamp(-y, 0, 1))
				UiSendInputScreenTouchAction("down", joystickTouchId, math.clamp(y, 0, 1))
			end
			UiSetScreenTouchIdHandled(joystickTouchId)
		end
		UiColor(1.0, 1.0, 1.0, 1.0)
		UiImageBox("ui/hud/touch/joystick_handle.png", joystickHandleSize, joystickHandleSize, 0, 0)
	UiPop()
end
