script_name('cornHUD')
script_author("Serhiy_Rubin")
script_version("22/09/2019")
require 'lib.sampfuncs'
require 'lib.moonloader'
local vkeys = require "lib.vkeys"
local sampev, inicfg = require 'lib.samp.events', require 'inicfg'
local render, antiflood = false, 0
local zerno, urojai, narko, priceZerno, priceUrojai, priceNarko, finfoCheck = 0, 0, 0, 0, 0, 0, 0
local coord = {
	['Farm 0'] = {x = -379.220367, y = -1425.855591, z = 25.862316 },
	['Farm 1'] = {x = -116.514381, y = 2.906076, z = 3.227722 },
	['Farm 2'] = {x = -1055.663330, y = -1203.198486, z = 129.136978 },
	['Farm 3'] = {x = -0.693013, y = 74.493423, z = 3.231136 },
	['Farm 4'] = {x = 1912.754150, y = 176.559540, z = 37.375542 },
	['Narko'] = {x = 2182.483887, y = -1657.505615, z = 15.201279 },
	['Zerno'] = {x = 2206.272949, y = -2245.668457, z = 13.661810 },
	['Urojai'] = {x = 972.86, y = 2105.53, z = 10.94 }
}

function main()
	if not isSampLoaded() or not isSampfuncsLoaded() then return end
	while not isSampAvailable() do wait(0) end
    repeat wait(0) until sampGetCurrentServerName() ~= "SA-MP"
    repeat wait(0) until sampGetCurrentServerName():find("Samp%-Rp.Ru") or sampGetCurrentServerName():find("SRP")
    server = sampGetCurrentServerName():gsub("|", "")
    server =
        (server:find("02") and "Two" or
        (server:find("Revo") and "Revolution" or
            (server:find("Legacy") and "Legacy" or (server:find("Classic") and "Classic" or
        (server:find("Zero Two") and "Two" or "")))))
    if server == "" then
        thisScript():unload()
    end
	iniName = string.format("corn-%s", server)
	local x1, y1 = convertGameScreenCoordsToWindowScreenCoords(14.992679595947, 274.75)
	ini = inicfg.load({
		['Farm 0'] = {
			corn = 0,
			cornPrice = 0,
			product = 0,
			productPrice = 0,
			bank = 0
		},
		['Farm 1'] = {
			corn = 0,
			cornPrice = 0,
			product = 0,
			productPrice = 0,
			bank = 0
		},
		['Farm 2'] = {
			corn = 0,
			cornPrice = 0,
			product = 0,
			productPrice = 0,
			bank = 0
		},
		['Farm 3'] = {
			corn = 0,
			cornPrice = 0,
			product = 0,
			productPrice = 0,
			bank = 0
		},
		['Farm 4'] = {
			corn = 0,
			cornPrice = 0,
			product = 0,
			productPrice = 0,
			bank = 0
		},
		price = {
			zerno = 0,
			urojai = 0,
			narko = 0
		},
		Render = {
			FontName='Segoe UI',
			FontSize=10,
			FontFlag=15,
			Color1='2f72f7',
			Color2='FFFFFF'
		},
		Settings = {
			Key1='VK_RBUTTON',
			Key2='VK_MENU',
			X=x1,
			Y=y1
		},
	}, iniName)
	inicfg.save(ini, iniName)
	sampfuncsLog(' {FFFFFF}corn-hud loaded. CMD: /corn | /corn hud. | Key combo: '..ini.Settings.Key1:gsub("VK_", '')..' + '..ini.Settings.Key2:gsub("VK_", ''))
	font = renderCreateFont(ini.Render.FontName, ini.Render.FontSize, ini.Render.FontFlag)
	lua_thread.create(menu.loop)
	while true do
		wait(0)
		points = ''
		for k,v in pairs(coord) do
			local dist = math.floor(getDistanceBetweenCoords3d(v.x, v.y, v.z, getCharCoordinates(playerPed)))
			if dist <= 30 then
				points = k
			end
		end
		if finfoCheck == 1 then
			if points:find('Farm') then
				if math.ceil(os.clock() * 1000 - antiflood) > 999 then
					finfoCheck = 2
					sampSendChat('/finfo')
				end
			else
				finfoCheck = 0
			end
		end
		if render then
			renderText = {
				[1] = '{00D900}���� ������� �����: '..ini.price.zerno..'$',
				[2] = '{00D900}���� ������� ������: '..ini.price.urojai..'$',
				[3] = '{00D900} ',
				[4] = string.format('{00D900}����� �0 | ������: %d$ | �����: %d [%d$] | ������: %d [%d$]', ini['Farm 0'].bank,  ini['Farm 0'].corn, ini['Farm 0'].cornPrice, ini['Farm 0'].product, ini['Farm 0'].productPrice),
				[5] = string.format('{00D900}����� �1 | ������: %d$ | �����: %s [%s$] | ������: %s [%s$]', ini['Farm 1'].bank,  ini['Farm 1'].corn, ini['Farm 1'].cornPrice, ini['Farm 1'].product, ini['Farm 1'].productPrice),
				[6] = string.format('{00D900}����� �2 | ������: %d$ | �����: %s [%s$] | ������: %s [%s$]', ini['Farm 2'].bank,  ini['Farm 2'].corn, ini['Farm 2'].cornPrice, ini['Farm 2'].product, ini['Farm 2'].productPrice),
				[7] = string.format('{00D900}����� �3 | ������: %d$ | �����: %s [%s$] | ������: %s [%s$]', ini['Farm 3'].bank,  ini['Farm 3'].corn, ini['Farm 3'].cornPrice, ini['Farm 3'].product, ini['Farm 3'].productPrice),
				[8] = string.format('{00D900}����� �4 | ������: %d$ | �����: %s [%s$] | ������: %s [%s$]', ini['Farm 4'].bank, ini['Farm 4'].corn, ini['Farm 4'].cornPrice, ini['Farm 4'].product, ini['Farm 4'].productPrice),
			}
			local X, Y = ini.Settings.X, ini.Settings.Y
			for i = 1, #renderText do
				renderFontDrawText(font, renderText[i], X, Y, -1)
				if i ~= 3 then
					Y = Y + (renderGetFontDrawHeight(font) - (renderGetFontDrawHeight(font) / 5))
				else
					Y = Y + (renderGetFontDrawHeight(font) / 5)
				end
			end
		end
		if isKeyDown(vkeys[ini.Settings.Key1]) and (isCharInModel(PLAYER_PED, 440) or isKeyDown(vkeys[ini.Settings.Key2])) then
			sampSetCursorMode(3)
			mouse = 1
			local posX, posY = getScreenResolution()
			local plus = (renderGetFontDrawHeight(font) + (renderGetFontDrawHeight(font) / 10))
			posX = posX / 2
			posY = ((posY / 2.2) - (renderGetFontDrawHeight(font) * 3))
			renderText = {
				[1] = (render and 'Corn-HUD: ON' or 'Corn-HUD: OFF'),
				[2] = '���������',
				[3] = '����������',
				[4] = '���������� � �����',
				[5] = '�������� ���������� � �����'
			}
			for i = 1, #renderText do
				if drawClickableText(renderText[i], posX - (renderGetFontDrawTextLength(font, renderText[i]) / 2), posY, 0xFF00D900, 0xFFFFFFFF) then
					if i == 1 then
						render = not render
					end
					if i == 2 then
						if points ~= '' then
							if points:find('Farm') then
								local warecorn = urojai
								local corn = ( (1500 - warecorn) < tonumber(ini[points].product) and (1500 - warecorn) or tonumber(ini[points].product) )
								sampSendChat('/cornmenu 2 '..corn)
								finfoCheck = 1
							end
							if points:find('Zerno') then
								sampSendChat('/cornmenu 0 '..(1500 - zerno))
							end
						end
					end
					if i == 3 then
						if points ~= '' then
							if points:find('Farm') then
								sampSendChat('/cornmenu 1 '..(zerno > (10000 - ini[points].corn) and (10000 - ini[points].corn) or zerno))
								finfoCheck = 1
							end
							if points:find('Narko') then
								sampSendChat('/cornmenu 4 '..narko)
							end
							if points:find('Urojai') then
								sampSendChat('/cornmenu 4 '..urojai)
							end
						end
					end
					if i == 4 then
						sampSendChat('/finfo')
					end
					if i == 5 then
						finfoCheck = 1
					end
				end

				posY = posY + plus
			end
		else
			if mouse ~= nil and mouse == 1 then
				sampSetCursorMode(0)
				mouse = nil
			end
		end
	end
end

function sampev.onServerMessage(color, message)
	if message:find(' �����: (%d+) / 1500') then
		zerno = tonumber(message:match(' �����: (%d+) / 1500'))
	end
	if message:find(' ������: (%d+) / 1500') then
		urojai = tonumber(message:match(' ������: (%d+) / 1500'))
	end
	if message:find(' ���������: (%d+) / 1500') then
		narko = tonumber(message:match(' ���������: (%d+) / 1500'))
	end
end

function sampev.onCreate3DText(id, color, position, distance, testLOS, attachedPlayerId, attachedVehicleId, text)
	if text:find('{FF8000}��������� ����������.*��������� ���������� (%d+) ����') then
		ini.price.narko = text:match('{FF8000}��������� ����������.*��������� ���������� (%d+) ����')
		inicfg.save(ini, iniName)
	end
	if text:find('{FF8000}�������� �����.*��������� ����� (%d+) ����.+') then
		ini.price.zerno = text:match('{FF8000}�������� �����.*��������� ����� (%d+) ����.+')
		inicfg.save(ini, iniName)
	end
	if text:find('{FF8000}��������� ������.*��������� ������ (%d+) ����') then
		ini.price.urojai = text:match('{FF8000}��������� ������.*��������� ������ (%d+) ����')
		inicfg.save(ini, iniName)
	end
end

function sampev.onShowDialog(dialogId, style, title, button1, button2, text)
	if text:find(".FBDD7E.������ �����:.FFFFFF.\t\t\t(%d+).+FBDD7E.������ � ������:.FFFFFF.\t\t\t(%d+) / %d+.+FBDD7E.������ �� ����:{FFFFFF}\t\t\t(%d+) / %d+.+FBDD7E.��������� � ������:.FFFFFF.\t\t\t(%d+) / %d+.+FBDD7E.���� �� ������:.FFFFFF.\t\t\t(%d+).+FBDD7E.���� �� ���������:.FFFFFF.\t\t\t(%d+)") then
		local S0 = CheckCoord()
		if S0 ~= '' then
			ini[S0].bank, ini[S0].corn, ini[S0].product, ini[S0].cornPrice, ini[S0].productPrice = text:match(".FBDD7E.������ �����:.FFFFFF.\t\t\t(%d+).+FBDD7E.������ � ������:.FFFFFF.\t\t\t(%d+) / %d+.+FBDD7E.������ �� ����:{FFFFFF}\t\t\t%d+ / %d+.+FBDD7E.��������� � ������:.FFFFFF.\t\t\t(%d+) / %d+.+FBDD7E.���� �� ������:.FFFFFF.\t\t\t(%d+).+FBDD7E.���� �� ���������:.FFFFFF.\t\t\t(%d+)")
			inicfg.save(ini, iniName)
			if finfoCheck ~= 0 then
				finfoCheck = 0
				return false
			end
		end
	end
	if text:find('{FFFFFF}����� �������: {0289CC}(%d+).*{FFFFFF}����: {0289CC}%d+ ����.*{FFFFFF}������: {0289CC}%d+ ����') then
		zerno = zerno + tonumber(text:match('{FFFFFF}����� �������: {0289CC}(%d+).*{FFFFFF}����: {0289CC}%d+ ����.*{FFFFFF}������: {0289CC}%d+ ����'))
		print(zerno)
	end
	if text:find('{FFFFFF}����� �������: {0289CC}(%d+).*{FFFFFF}����: {0289CC}%d+ ����.*{FFFFFF}��������� � ��: {0289CC}%d+ ����') then
		zerno = zerno - tonumber(text:match('{FFFFFF}����� �������: {0289CC}(%d+).*{FFFFFF}����: {0289CC}%d+ ����.*{FFFFFF}��������� � ��: {0289CC}%d+ ����'))
		print(zerno)
	end
	if text:find('{FFFFFF}������ �������: {0289CC}(%d+).*{FFFFFF}����: {0289CC}%d+ ����') then
		urojai = urojai + tonumber(text:match('{FFFFFF}������ �������: {0289CC}(%d+).*{FFFFFF}����: {0289CC}%d+ ����'))
		print(urojai)
	end
	if text:find('������ �������: {0289CC}(%d+).*{FFFFFF}����: {0289CC}%d+ ����') then
		urojai = urojai - tonumber(text:match('������ �������: {0289CC}(%d+).*{FFFFFF}����: {0289CC}%d+ ����'))
		print(urojai)
	end
	if text:find('{FFFFFF}���������� �������: {0289CC}(%d+).*{FFFFFF}����: {0289CC}%d+ ����') then
		narko = narko + tonumber(text:match('{FFFFFF}���������� �������: {0289CC}(%d+).*{FFFFFF}����: {0289CC}%d+ ����'))
	end
	if text:find('���������� �������: {0289CC}(%d+)') then
		narko = narko - tonumber(text:match('���������� �������: {0289CC}(%d+)'))
	end
end

function sampev.onSendChat(message) antiflood = os.clock() * 1000 end
function sampev.onSendCommand(cmd) antiflood = os.clock() * 1000 end

function CheckCoord()
	for k,v in pairs(coord) do
		local dist = math.floor(getDistanceBetweenCoords3d(v.x, v.y, v.z, getCharCoordinates(playerPed)))
		if dist <= 30 then
			return k
		end
	end
	return ''
end

function drawClickableText(text, posX, posY, Color1, Color2)
    if text ~= nil and posX ~= nil and posY ~= nil then
        renderFontDrawText(font, text, posX, posY, Color1)
        local textLenght = renderGetFontDrawTextLength(font, text)
        local textHeight = renderGetFontDrawHeight(font)
        local curX, curY = getCursorPos()
        if curX >= posX and curX <= posX + textLenght and curY >= posY and curY <= posY + textHeight then
			renderFontDrawText(font, text, posX, posY, Color2)
			if isKeyJustPressed(1) then
				return true
			else
				return false
			end
        end
    else
        return false
    end
end


-->> MENU
menu = {}

function menu.get()
	return {
		{
			settings = {title = "corn-hud" ,style = 4 ,btn1 = "�������" ,btn2 = "�������" ,forward =  "{ffffff}" ,backwards = "\n" ,score = true},
			{
				{
					title = 'HUD\t'..(render and "ON" or "OFF"),
					click = function(button, list, input , outs)
						if button ~= 1 then return end
						render = not render
						showMenu = true
					end
				},
				{
					title = '������� �������\t',
					click = function(button, list, input , outs)
						if button ~= 1 then return end
						if not render then
							render = true
						end
						wait(200)
						repeat
							wait(0)
							sampSetCursorMode(3)
							local X, Y = getCursorPos()
							ini.Settings.X = X
							ini.Settings.Y = Y
						until isKeyJustPressed(1)
							inicfg.save(ini, iniName)
						sampSetCursorMode(0)
						showMenu = true
					end
				},
				{
					title = '������� �1\t'..ini.Settings.Key1:gsub("VK_", ""),
					click = function(button, list, input , outs)
						if button ~= 1 then return end
						wait(200)
						local key = ""
						repeat
							wait(0)
							if not sampIsDialogActive() then
								sampShowDialog(0, "����� ���������", "������� �� ����� �������", "�������", "�������", 0)
							end
							for k, v in pairs(vkeys) do
								if wasKeyPressed(v) and k ~= "VK_ESCAPE" and k ~= "VK_RETURN" then
									key = k
								end
							end
						until key ~= ""
						ini.Settings.Key1 = key
						inicfg.save(ini, iniName)
						showMenu = true
					end
				},
				{
					title = '������� �2\t'..ini.Settings.Key2:gsub("VK_", ""),
					click = function(button, list, input , outs)
						if button ~= 1 then return end
						wait(200)
						local key = ""
						repeat
							wait(0)
							if not sampIsDialogActive() then
								sampShowDialog(0, "����� ���������", "������� �� ����� �������", "�������", "�������", 0)
							end
							for k, v in pairs(vkeys) do
								if wasKeyPressed(v) and k ~= "VK_ESCAPE" and k ~= "VK_RETURN" then
									key = k
								end
							end
						until key ~= ""
						ini.Settings.Key2 = key
						inicfg.save(ini, iniName)
						showMenu = true
					end
				},
			}
		}
	}
end

function menu.loop()
	showMenu = false
	sampRegisterChatCommand('corn', function(param)
		showMenu = true
	end)
	while true do
		wait(0)
		if showMenu then
			showMenu = false
			menu.dialog = menu.get()
			start_dialog(menu.dialog[1])
		end
	end
end

function start_dialog(menu) -- module by trefa
    function _dialog(menu, id,  outs)
        sampShowDialog(id, menu.settings.title, tbl_split(menu.settings.style, menu, menu.settings.forward ,menu.settings.backwards ,menu.settings.score), menu.settings.btn1, (menu.settings.btn2 ~= nil and menu.settings.btn2 or _), menu.settings.style)
            repeat
                wait(0)
                local result, button, list, input = sampHasDialogRespond(id)
                if result then
                    local out, outs = menu[((menu.settings.style == 0 or menu.settings.style == 1 or menu.settings.style == 3) and 1 or ((list + 1) > #menu[1] and 2 or 1))][((menu.settings.style == 0 or menu.settings.style == 1 or menu.settings.style == 3) and 1 or ((list + 1) > #menu[1] and (list - #menu[1]) + 1  or list + 1))].click(button, list, input, outs)
                    if type(out) == "table" then
                        return _dialog(out, id - 1, outs)
                    elseif type(out) == "boolean" then
                        if not out then
                            return out
                        end
                            return _dialog(menu, id, outs)
                    end
                end
            until result
    end

    function tbl_split(style, tbl, forward ,backwards ,score)
        if style == 2 or style == 4 or style == 5 then
            text = (style == 5 and tbl[1].text.."\n" or "")
            for i, val in ipairs(tbl[1]) do
                text = text..""..forward..""..(score and "["..(i-1).."] " or "")..""..val.title..""..backwards
            end
            if tbl[2] ~= nil then
                for _, val in ipairs(tbl[2]) do
                    text = text..""..forward..""..val.title..""..backwards
                end
            end
            return text
        end
        return tbl[1].text
    end

    return _dialog(menu, 1337, outs)
end