require("scripts.colorpicker.customformats")

local orientations_map = {
	[TR("Home On Bottom")] = 0,
	[TR("Home On Right")] = 1,
	[TR("Home On Left")] = 2,
	[TR("Home On Top")] = 3,
}

return {
	name = "X, Y, Color",
	description = TR("X, Y, Color"),
	formats = {
		settingsRule = {
			title = TR("Parameter settings for the custom format [X, Y, Color]"),
			args = {
				{TR("Default Color Similarity"),
				 85, -- 默认值为数字，且第三个参数用一个表描述范围则用一个 Slider（滑动条） 描述
				 {
					 10,  -- Slider 的最小值
					 100, -- Slider 的最大值
				 },
				},
				{TR("Aligning Using Spaces"), true}, -- 默认值是布尔类型则控件用 CheckBox（勾选框） 描述
				{TR("Using Line Break"), true},
				{TR("Color Offset Mode"), false},
				{TR("Default Color Offset"), 101010}, -- 默认值是字符串或者数字且没有第三个参数则用 TextFeild（文本框） 描述
				{TR("XXTDo Action"),
				 TR("Tap the last point in the PosColor list"),
				 {
					 TR("Tap the first point in the PosColor list"),
					 TR("Tap the last point in the PosColor list"),
					 TR("Tap point A"),
					 TR("Tap point S"),
					 TR("Tap point X"),
					 TR("Tap point C"),
					 TR("Execute Custom Code"),
				 },
				},
				{TR("XXTDo Action Custom Code"), "local ui = type(self.group) == 'table' and self.group[1] or self;touch.tap(ui[#ui][1], ui[#ui][2])"},
				{TR("Orientation During Testing"),
				 TR("Home On Bottom"),
				 {
					 TR("Home On Bottom"),
					 TR("Home On Right"),
					 TR("Home On Left"),
					 TR("Home On Top"),
				 },
				},
				{"ComboBox 1",
				 "Option 1", -- Default, string value
				 { -- Option List, table value
					 "Option 1",
					 "Option 2",
					 "Option 3",
				 },
				 false, -- Editable, boolean value
				},
				{"CheckBox 2", true},
				{"TextField 3", "TextField Contents"},
				{"Slider 4",
				 5, -- Default, number value
				 { -- Range, table value
					 0,  -- Min, number value
					 30, -- Max, number value
					 5,  -- Step, number value
				 },
				},
			},
		},
		singlePosFormatRule = (function(p, a, s, x, c, set)
			local fmt = string.format("%4d, %4d, 0x%06x ", p.x, p.y, p.c)
			if not toboolean(set[TR("Aligning Using Spaces")]) then
				fmt = fmt:gsub(" ", "")
			end
			return fmt
		end),
		multiPosFormatRule = (function(p, a, s, x, c, set)
			local fmt = string.format(" %4d, %4d, 0x%06x \n", p.x, p.y, p.c)
			if not toboolean(set[TR("Using Line Break")]) then
				fmt = fmt:gsub("\n", ""):gsub("\t", "")
			end
			if not toboolean(set[TR("Aligning Using Spaces")]) then
				fmt = fmt:gsub(" ", "")
			end
			return fmt
		end),
		mouseTrackInfoBottomRule = (function(p, a, s, x, c, set)
			return string.format("XY: (%4d, %4d)      Color: 0x%06x      RGB: (%3d, %3d, %3d)", p.x, p.y, p.c, p.r, p.g, p.b)
		end),
		mouseTrackInfoZoomRule = (function(p, a, s, x, c, set)
			return string.format("(%4d,%4d):0x%06x:(%3d,%3d,%3d)", p.x, p.y, p.c, p.r, p.g, p.b)
		end),
		makeScriptRules = {
			{
				maker = function(poslist, set)
					local fmt = "\t{ %4d, %4d, 0x%06x},\n"
					if #poslist < 1 then
						return "{}: "..TR("Need to take at least 1 PosColor")
					end
					local ret = "{\n"
					for _,currentPos in ipairs(poslist) do
						ret = ret..string.format(fmt, currentPos.x, currentPos.y, currentPos.c)
					end
					ret = ret.."}"
					if not toboolean(set[TR("Using Line Break")]) then
						ret = ret:gsub("\n", ""):gsub("\t", "")
					end
					if not toboolean(set[TR("Aligning Using Spaces")]) then
						ret = ret:gsub(" ", "")
					end
					return ret
				end,
				menu = {
					{
						name = TR("Format Readme"),
						action = function(s, idx, poslist, set)
							alert(TR("A general point color table, used in various script frameworks, which requires developers to parse and use it themselves"), TR("Format Readme"))
						end,
					},
				},
			},
			{
				maker = function(poslist, set)
					local fmt = "{ %4d, %4d, 0x%06x},\n"
					if #poslist < 1 then
						return TR("Need to take at least 1 PosColor")
					end
					local ret = ""
					for _,currentPos in ipairs(poslist) do
						ret = ret..string.format(fmt, currentPos.x, currentPos.y, currentPos.c)
					end
					ret = ret..""
					if not toboolean(set[TR("Using Line Break")]) then
						ret = ret:gsub("\n", ""):gsub("\t", "")
					end
					if not toboolean(set[TR("Aligning Using Spaces")]) then
						ret = ret:gsub(" ", "")
					end
					return ret
				end,
				menu = {
					{
						name = TR("Format Readme"),
						action = function(s, idx, poslist, set)
							alert(TR("A general point color table, used in various script frameworks, which requires developers to parse and use it themselves"), TR("Format Readme"))
						end,
					},
				},
			},
			{
				maker = function(poslist, set)
					local fmt = "\t\t\t{ %4d, %4d, 0x%06x},\n"
					if #poslist < 1 then
						return "XXTDo: "..TR("Need to take at least 1 PosColor")
					end
					local ret = string.format("{name = '__UI_%s__', group = {\n\t\t", os.date('%Y%m%d%H%M%S'))
					local cen = "{\n"
					for _,currentPos in ipairs(poslist) do
						cen = cen..string.format(fmt, currentPos.x, currentPos.y, currentPos.c)
					end
					cen = cen.."\t\t},"
					if not toboolean(set[TR("Aligning Using Spaces")]) then
						cen = cen:gsub(" ", "")
					end
					if not toboolean(set[TR("Using Line Break")]) then
						cen = cen:gsub("\n", ""):gsub("\t", "")
					end
					-- {TR("Tap the first point in the PosColor list"), TR("Tap the last point in the PosColor list"), TR("Tap point A"), TR("Tap point S"), TR("Tap point X"), TR("Tap point C"), TR("Execute Custom Code")},
					ret = ret..cen.."\n\t},\n\trun = function(self, index, parent)"
					local act = "\n\t\t"
					if set[TR("XXTDo Action")] == TR("Tap the first point in the PosColor list") then
						act = act..string.format("touch.tap(%d, %d)", poslist[1].x, poslist[1].y)
					elseif set[TR("XXTDo Action")] == TR("Tap the last point in the PosColor list") then
						act = act..string.format("touch.tap(%d, %d)", poslist[#poslist].x, poslist[#poslist].y)
					elseif set[TR("XXTDo Action")] == TR("Tap point A") then
						act = act..string.format("touch.tap(%d, %d)", poslist.a.x, poslist.a.y)
					elseif set[TR("XXTDo Action")] == TR("Tap point S") then
						act = act..string.format("touch.tap(%d, %d)", poslist.s.x, poslist.s.y)
					elseif set[TR("XXTDo Action")] == TR("Tap point X") then
						act = act..string.format("touch.tap(%d, %d)", poslist.x.x, poslist.x.y)
					elseif set[TR("XXTDo Action")] == TR("Tap point C") then
						act = act..string.format("touch.tap(%d, %d)", poslist.c.x, poslist.c.y)
					end
					if set[TR("XXTDo Action")] == TR("Execute Custom Code") then
						act = act..string.format("%s", set[TR("XXTDo Action Custom Code")] or "")
						act = act.."\n\t"
					else
						act = act.."\n\t"
						if not toboolean(set[TR("Aligning Using Spaces")]) then
							cen = cen:gsub(" ", "")
						end
						if not toboolean(set[TR("Using Line Break")]) then
							act = act:gsub("\n", ""):gsub("\t", "")
						end
					end
					ret = ret..act
					if not toboolean(set[TR("Using Line Break")]) then
						ret = ret.." " -- 不是换行格式在 end 前加个空格
					end
					ret = ret.."end,\n},\n"
					return ret
				end,
				menu = {
					{
						name = TR("Format Readme"),
						action = function(s, idx, poslist, set)
							alert(TR("Generate an interface trigger for use by the XXTDo\nUse with the XXTDo"), TR("Format Readme"))
						end,
					},
					{
						name = TR("Test On Device"),
						action = function(s, idx, poslist, set)
							local code = string.format("local o = %d;screen.init(o);nLog('[TEST]: screen.init('..o..')')\n", tonumber(orientations_map[set[TR("Orientation During Testing")]]) or 0)
							code = code .. [[success, XXTDo = pcall(require, 'XXTDo')
							if not success then
							    XXT_HOME_PATH = XXT_HOME_PATH or '/var/mobile/Media/1ferver'
								local XXTDoPath = XXT_HOME_PATH..'/lua/XXTDo.lua'
								nLog("[TEST] XXTDo: "..]] ..string.format("%q", TR("Testing code changes requires XXTDo.lua")).. [[)
								local ip, port = nLog()
								local success, c, h, r = pcall(http.get, string.format('http://%s:%d/XXTDo.lua', ip, port))
								if success and c == 200 then
									file.writes(XXTDoPath, r)
									nLog("[TEST] XXTDo: "..string.format(]]..string.format("%q", TR("Automatically importing XXTDo.lua to device path '%s'"))..[[, XXTDoPath))
									success, XXTDo = pcall(require, 'XXTDo')
									if not success then
										os.remove(XXTDoPath)
										nLog("[TEST] XXTDo: "..string.format(]]..string.format("%q", TR("Automatic import of XXTDo.lua failed\nPlease manually import XXTDo.lua to the device path '%s'"))..[[, XXTDoPath))
										os.exit()
									end
								else
									nLog("[TEST] XXTDo: "..string.format(]]..string.format("%q", TR("Automatic import of XXTDo.lua failed\nPlease manually import XXTDo.lua to the device path '%s'"))..[[, XXTDoPath))
									os.exit()
								end
							end
							nLog("[TEST] XXTDo: "..]]..string.format("%q", TR("The timeout is set to 5 seconds. If no match is found within the timeout, the matching loop will be exited"))..[[)
							XXTDo.runloop{name = "XXTColorPicker-TestOnDevice",
							log = nLog, timeout_s = 5, timeout_run = function() XXTDo.breakloop() end, error = function(errmsg) nLog("[TEST] XXTDo: RuntimeError: ", json.decode(errmsg)) os.exit() end,]]
							code = code..s..[[}]]
							if load(code) then
								Java.newThread(function()
									uploadScriptAndRun(code)
								end):start()
							else
								alert(TR("Please generate custom code as required"), TR("Cannot Test"))
							end
						end,
					},
				},
			},
			{
				maker = function(poslist, set)
					if #poslist < 1 then
						return "is_colors: "..TR("Need to take at least 1 PosColor")
					end
					local ret = "if (screen.is_colors({\n"
					for i,currentPos in ipairs(poslist) do
						ret = ret..string.format("\t{%4d, %4d, 0x%06x },\n", currentPos.x, currentPos.y, currentPos.c)
					end
					ret = ret.."}, "..set[TR("Default Color Similarity")]..")) then"
					if not toboolean(set[TR("Using Line Break")]) then
						ret = ret:gsub("\n", ""):gsub("\t", "")
					end
					if not toboolean(set[TR("Aligning Using Spaces")]) then
						ret = ret:gsub(" ", "")
					end
					return ret
				end,
				menu = {
					{
						name = TR("Format Readme"),
						action = function(s, idx, poslist, set)
							alert(TR("This format is dedicated to the function screen.is_colors defined by XXTouch"), TR("Format Readme"))
						end,
					},
					{
						name = TR("Test On Device"),
						action = function(s, idx, poslist, set)
							local code = string.format("local o = %d;screen.init(o);nLog('[TEST]: screen.init('..o..')')\n", tonumber(orientations_map[set[TR("Orientation During Testing")]]) or 0)
							code = code .. isColorCodeDefine..s..[[
									nLog("[TEST] screen.is_colors results: true")
								else
									nLog("[TEST] screen.is_colors results: false")
								end
							]]
							if load(code) then
								Java.newThread(function()
									uploadScriptAndRun(code)
								end):start()
							else
								alert(TR("Please generate custom code as required"), TR("Cannot Test"))
							end
						end,
					},
				},
			},
			{
				maker = function(poslist, set)
					if #poslist < 1 then
						return "find_color-1: "..TR("Need to take at least 1 PosColor")
					end
					local ret = "x, y = screen.find_color({\n"
					for i,currentPos in ipairs(poslist) do
						if toboolean(set[TR("Color Offset Mode")]) then
							ret = ret..string.format("\t{%4d, %4d, {0x%06x, 0x%06x} },\n", currentPos.x, currentPos.y, currentPos.c, (tonumber(set["默认色偏"], 16) or 0x101010))
						else
							ret = ret..string.format("\t{%4d, %4d, 0x%06x },\n", currentPos.x, currentPos.y, currentPos.c)
						end
					end
					if toboolean(set[TR("Color Offset Mode")]) then
						ret = ret.."}"
					else
						ret = ret.."}, "..tostring(tonumber(set[TR("Default Color Similarity")]) or 90)
					end
					if (0 ~= poslist.a.x) and
							(0 ~= poslist.a.y) and
							(0 ~= poslist.s.x) and
							(0 ~= poslist.s.y) then
						ret = ret..string.format(", %4d, %4d, %4d, %4d", poslist.a.x, poslist.a.y, poslist.s.x, poslist.s.y)
					end
					ret = ret..")"
					if not toboolean(set[TR("Using Line Break")]) then
						ret = ret:gsub("[\n\t]", "")
					end
					if not toboolean(set[TR("Aligning Using Spaces")]) then
						ret = ret:gsub(" ", "")
					end
					return ret
				end,
				menu = function(s, idx, poslist, set)
					if load(s) then
						return {
							{
								name = TR("Format Readme"),
								action = function(s, idx, poslist, set)
									alert(TR("This format is specially used for the function screen.find_color defined by XXTouch\nAll coordinates captured are absolute coordinates"), TR("Format Readme"))
								end,
							},
							{
								name = TR("Test On Device"),
								action = function(s, idx, poslist, set)
									local code = string.format("local o = %d;screen.init(o);nLog('[TEST]: screen.init('..o..')')\n", tonumber(orientations_map[set[TR("Orientation During Testing")]]) or 0)
									code = code .. s ..[[
										nLog("[TEST] screen.find_color results: "..tostring(x)..", "..tostring(y))
									]]
									if load(code) then
										Java.newThread(function()
											uploadScriptAndRun(code)
										end):start()
									else
										alert(TR("Please generate custom code as required"), TR("Cannot Test"))
									end
								end,
							},
						}
					end
				end,
			},
			{
				maker = function(poslist, set)
					if #poslist < 1 then
						return "find_color-2: "..TR("Need to take at least 1 PosColor")
					end
					local ret = "x, y = screen.find_color({\n"
					local firstPos
					for i,currentPos in ipairs(poslist) do
						if (1 == i) then
							firstPos = currentPos
							if toboolean(set[TR("Color Offset Mode")]) then
								ret = ret..string.format("\t{%4d, %4d, {0x%06x, 0x%06x} },\n", 0, 0, firstPos.c, (tonumber(set["默认色偏"], 16) or 0x101010))
							else
								ret = ret..string.format("\t{%4d, %4d, 0x%06x },\n", 0, 0, firstPos.c)
							end
						else
							ret = ret..string.format("\t{%4d, %4d, 0x%06x },\n", currentPos.x - firstPos.x, currentPos.y - firstPos.y, currentPos.c)
						end
					end
					if toboolean(set[TR("Color Offset Mode")]) then
						ret = ret.."}"
					else
						ret = ret.."}, "..tostring(tonumber(set[TR("Default Color Similarity")]) or 90)
					end
					if (0 ~= poslist.a.x) and
							(0 ~= poslist.a.y) and
							(0 ~= poslist.s.x) and
							(0 ~= poslist.s.y) then
						ret = ret..string.format(", %4d, %4d, %4d, %4d", poslist.a.x, poslist.a.y, poslist.s.x, poslist.s.y)
					end
					ret = ret..")"
					if not toboolean(set[TR("Using Line Break")]) then
						ret = ret:gsub("[\n\t]", "")
					end
					if not toboolean(set[TR("Aligning Using Spaces")]) then
						ret = ret:gsub(" ", "")
					end
					return ret
				end,
				menu = function(s, idx, poslist, set)
					if load(s) then
						return {
							{
								name = TR("Format Readme"),
								action = function(s, idx, poslist, set)
									alert(TR("This format is specially used for the function screen.find_color defined by XXTouch\nOnly relative coordinates are captured"), TR("Format Readme"))
								end,
							},
							{
								name = TR("Test On Device"),
								action = function(s, idx, poslist, set)
									local code = string.format("local o = %d;screen.init(o);nLog('[TEST]: screen.init('..o..')')\n", tonumber(orientations_map[set[TR("Orientation During Testing")]]) or 0)
									code = code .. s ..[[
										nLog("[TEST] screen.find_color results: "..tostring(x)..", "..tostring(y))
									]]
									if load(code) then
										Java.newThread(function()
											uploadScriptAndRun(code)
										end):start()
									else
										alert(TR("Please generate custom code as required"), TR("Cannot Test"))
									end
								end,
							},
						}
					end
				end,
			},
			{
				maker = function(poslist, set)
					local tl = poslist.a
					local br = poslist.s
					if br.x <= tl.x and br.y <= tl.y then
						return "ocr_text: "..TR("Please use [Shift + left mouse button] to select an rect on the image")
					end
					return string.format("txt, info = screen.ocr_text(%d, %d, %d, %d, {lang = 'eng'})", tl.x, tl.y, br.x, br.y)
				end,
				menu = {
					{
						name = TR("Format Readme"),
						action = function(s, idx, poslist, set)
							alert(TR("This format is specially used for the screen.ocr_text screen text recognition function defined by XXTouch\nUse [Shift + left mouse button] to select the text area that needs to be recognized"), TR("Format Readme"))
						end,
					},
					{
						name = TR("Test On Device"),
						action = function(s, idx, poslist, set)
							local code = string.format("local o = %d;screen.init(o);nLog('[TEST]: screen.init('..o..')')\n", tonumber(orientations_map[set[TR("Orientation During Testing")]]) or 0)
							code = code .. s ..[[
								nLog("[TEST] screen.ocr_text results: ", txt, info)
							]]
							if load(code) then
								Java.newThread(function()
									uploadScriptAndRun(code)
								end):start()
							else
								alert(TR("Please generate custom code as required"), TR("Cannot Test"))
							end
						end,
					},
				},
			},
			{
				maker = function(poslist, set)
					local a = poslist.a
					local s = poslist.s
					local x = poslist.x
					local c = poslist.c
					local ex, ey = getImageSize()
					if a.x~=s.x and a.y~=s.y and a.x > 0 and a.y > 0 and s.x < ex and s.y < ey then
						--					local function s2h(s,cp)return(string.gsub(s,"(.)",function(c)return string.format("\\x%02x%s",string.byte(c),cp or"")end))end
						--					return 'local x, y = screen.find_image( -- '..string.format("TR: %d, %d | BR: %d, %d", a.x, a.y, s.x, s.y)..'\n"'..s2h(getRectPNGData(a.x, a.y, s.x, s.y))..'"\n, 95, __这里替换成区域__)'
						local noerr, xdata = pcall(getRectPNGDataHex, a.x, a.y, s.x, s.y)
						if noerr then
							if (not (x.x==x.y and c.x==c.y)) and -- 区域不为 0, 0, 0, 0
									x.x~=c.x and x.y~=c.y and x.x > 0 and x.y > 0 and --[[c.x < ex and c.y < ey and--]]
									x.x<=a.x and x.y<=a.y and c.x>=s.x and c.y>=s.y -- XC选区范围大于AS选区
							then
								return 'x, y = screen.find_image( -- '..string.format("TL: %d, %d | BR: %d, %d", a.x, a.y, s.x, s.y)..'\n"'..xdata..'"\n, 95, '..string.format("%d, %d, %d, %d)", x.x, x.y, c.x, c.y)
							else
								return 'x, y = screen.find_image( -- '..string.format("TL: %d, %d | BR: %d, %d", a.x, a.y, s.x, s.y)..'\n"'..xdata..'"\n, 95, __RECT__)'
							end
						else
							alertError(xdata)
							return TR("Code generation failed")
						end
					else
						return "find_image: "..TR("Please use [Shift + left mouse button] to select an rect on the image")
					end
				end,
				menu = {
					{
						name = TR("Format Readme"),
						action = function(s, idx, poslist, set)
							alert(TR("This format is specially used for the function screen.find_image defined by XXTouch to find images in area or full screen\nUse [Shift + left mouse button] to select the image block to be found\nUse [Ctrl + left mouse button] to select the image search area"), TR("Format Readme"))
						end,
					},
					{
						name = TR("Test On Device"),
						action = function(s, idx, poslist, set)
							local code = string.format("local o = %d;screen.init(o);nLog('[TEST]: screen.init('..o..')')\n", tonumber(orientations_map[set[TR("Orientation During Testing")]]) or 0)
							code = code .. s ..[[
							nLog("[TEST] screen.find_image results: "..tostring(x)..", "..tostring(y))
							]]
							if load(code) then
								Java.newThread(function()
									uploadScriptAndRun(code)
								end):start()
							else
								alert(TR("Please generate custom code as required"), TR("Cannot Test"))
							end
						end,
					},
				},
			},
		},
	},
}