--20200512
require("libs.utils_new")
require("libs.utils_interface")

local JSONs = require("libs.JSON")
local Enum = GetEnums()
local key = nil
local hook = nil
local disconnect = nil
local menu = nil local skins_button = nil local skins_button_close = -1
local img = {}
local info_tab = {base={},decode={}}
local top_role = {init = false}

local player_connect_full = false
local full = nil
local select_match_id = 0
local screen = dota.GetScreenSize()
local lang = dota.GetLanguage()
local rate = screen.x/1600
local rate_y = screen.y/900
local DF15 = d3d.CreateFont("Arial", math.floor(16*rate), 0) local DF14 = d3d.CreateFont("Arial", math.floor(15*rate), 0)
local DF13 = d3d.CreateFont("Arial", math.floor(14*rate), 0) local DF11 = d3d.CreateFont("Arial", math.floor(10*rate), 0)
local FONT11 = d3d.CreateFont("Arial", math.floor(11*rate_y), 0)
local auto_stats = CFG:Read("Statistic","AutoOpen",true)
local auto_dotabuff = CFG:Read("Statistic","OpendDB",false)
local auto_odota = CFG:Read("Statistic","PriorityDB",false)

local blocked = {}

local players_color = {
	0x415fffff,
	0x83ffdaff,
	0xc3009cff,
	0xd5ff16ff,
	0xf16900ff,
	0xff6ca5ff,
	0x85c83bff,
	0x74d6f9ff,
	0x009e31ff,
	0x8f6f00ff,
}


function OnTick()

	local localplayer = dota.GetLocalPlayer()
	if not localplayer then
		return
	end

	local game_state = dota.GetGameState()
	if game_state==Enum.GAME_STATE_INIT then
		return
	end

	menu.visible = true

	if full and full<dota.GetTick() then
		if not img.bg then
			Dotabuff_OFF()
		end full = nil
	end

	menu.color = IsMouseOnButton(menu) and 0xffffffff or 0xffffff60
	ControleSkinCHange(game_state,localplayer)
	ShowRole()

	if not img.bg then
		return
	end

	if IsMouseOnButton(img.bg_close) then
		img.bg_close.color = 0xffffffff
	else
		img.bg_close.color = 0x999999ff
	end

	local allPlayers = dota.FindEntities(dota.kDotaPlayer)

	if localplayer==2 then
		table.sort( allPlayers, function (a,b) return a:GetTeamIndex() > b:GetTeamIndex() end)
	else
		table.sort( allPlayers, function (a,b) return a:GetTeamIndex() < b:GetTeamIndex() end)
	end

	-- if log.ProfileLastSteamId() ~= 0 then 
	-- 	local find_steamid = table.find(allPlayers,function (x) return x:GetSteamId()==log.ProfileLastSteamId() end)
	-- 	if find_steamid then
	-- 		allPlayers = table.filter(allPlayers,function (x) return x:GetSteamId()~=log.ProfileLastSteamId() end)
	-- 	end 
	-- 	allPlayers[#allPlayers+1] = find_steamid
	-- end 

	local temp = {team={},slots={}} temp.team[2] = {} temp.team[3] = {}

	for z,v in ipairs(allPlayers) do
		local i = v:GetPlayerId()
		local pinfo = v:GetPlayerInfo()
		if pinfo then
			pinfo:SetPlayInfoState(true)
			--v:SendHiddenInfo()

			local heroID = dota.PlayerResource.GetInstance():GetHeroId(i)

			local heroName = FindHero(heroID)
			local team_index = nil

			temp.team,team_index = FixTeamIndex(temp.team,v:GetTeamIndex())

			local _yy
			_yy,temp.slots = GetPlayersCount(i,team_index,temp.slots)
			local yy = img.bg.y+65*rate+30*rate*(_yy)+(team_index-2)*45*rate

			if _yy then

			if not img[i] then
				img[i] = {}
				img[i].last = {}
				img[i].most = {}
				img[i].party = {}

				local start_team = "npc_dota_hero_default"

				img[i].icon = d3d.CreateRect(img.player.x-55*rate,yy-6*rate,45*rate,25*rate,0xffffffff,true,GetTextureId2(start_team)) img[i].icon.visible = true
				img[i].icon_color = d3d.CreateRect(img[i].icon.x-2,yy-6*rate,2,25*rate,0xffffffff,true,0)
				img[i].nick = d3d.CreateText(img.player.x-2*rate,yy,0xFFFFFFFF,GetPlayerNormalName(v,DF13),DF13)

				img[i].location = d3d.CreateRect(img.MMR.x+42*rate,yy+50*rate,25*rate,25*rate,0xFFFFFF00,false,0) img[i].location.visible = false
				img[i].location2 = d3d.CreateRect(img[i].location.x,yy-6*rate,25*rate,25*rate,0xFFFFFF00,false,0) img[i].location.visible = false

				img[i].rating = d3d.CreateText(img.MMR.x+25*rate,yy-2*rate,0xAAAAffFF,"",DF13) img[i].rating.center = true
				img[i].gamse = d3d.CreateText(img.games.x+0*rate,yy-1*rate,0xFFFFFFFF,"",DF13) img[i].gamse.center = true
				img[i].gamse_wr = d3d.CreateText(img[i].gamse.x,yy+7*rate,0xFFFFFFFF,"",DF11) img[i].gamse_wr.center = true
				--last matches
				local last_x = img.lastGames.x-225*rate
				for z = 1, 7 do
					img[i].last[z] = {}
					img[i].last[z].icons =d3d.CreateRect(last_x+50*rate+50*rate*z,img[i].icon.y,42*rate,24*rate,0xffffffaa,true,GetTextureId2(start_team))
					RoundedImage(img[i].last[z].icons,0,0x000000aa,3)
					img[i].last[z].kill = d3d.CreateRect(last_x+50*rate+50*rate*z+2,img[i].icon.y+24*rate,39*rate,2*rate,0x101010aa,false,0) img[i].last[z].kill.visible = false
					img[i].last[z].dead = d3d.CreateRect(last_x+50*rate+50*rate*z+2,img[i].icon.y+24*rate,39*rate,2*rate,0xffffffff,false,0) img[i].last[z].dead.visible = false
				end
				--most played
				last_x = last_x + 100*rate
				for z = 1,3 do
					img[i].most[z] = {}
					img[i].most[z].icons = d3d.CreateRect(last_x+60*rate+64*rate*(z+4),img[i].icon.y+1,24*rate,25*rate,0xffffffff,true,GetTextureId2("panorama/images/hero_selection/unknown_hero_icon_png.vtex_c"))
					img[i].most[z].games = d3d.CreateText(last_x+95*rate+64*rate*(z+4),img[i].icon.y+1*rate,0xFFFFFFFF,"",DF13) img[i].most[z].games.visible = false
					img[i].most[z].win = d3d.CreateText(last_x+95*rate+64*rate*(z+4),img[i].icon.y+13*rate,0xFFFFFFFF,"",DF11) img[i].most[z].win.visible = false
					--img[i].party[z] = d3d.CreateRect(0,0,0,0,0xffffffff,true,0) img[i].party[z].visible = false
				end

				img[i].hero = d3d.CreateRect(last_x+60*rate+64*rate*8.4,img[i].icon.y+1,24*rate,25*rate,0xffffffff,true,0) img[i].hero.visible = false
				img[i].hero_game = d3d.CreateText(last_x+95*rate+64*rate*8.4,img[i].icon.y+1*rate,0xFFFFFFFF,"",DF13) img[i].hero_game.visible = false
				img[i].hero_win = d3d.CreateText(last_x+95*rate+64*rate*8.4,img[i].icon.y+13*rate,0xFFFFFFFF,"",DF11) img[i].hero_win.visible = false

				img[i].rect = d3d.CreateRect(img[i].icon.x,img[i].icon.y,img.bg.w-200*rate,25*rate,0xffffff20,true,0)
				if localplayer and i == localplayer:GetPlayerId() then
					img[i].nick.color = 0x25FF25FF
				end
				--if 
			else

				local ok, res = xpcall(function() return SafeCall(heroName,heroID,v,i,yy,localplayer,allPlayers) end, debug.traceback)

				if not ok then
					blocked[i] = true
					aaa("statistic error")
					aaa(res)
				end

			end

			end
		end
	end

	if #img.BestBanList==0 then
		return
	end

	for i = 1, math.min(5,#img.BestBanList) do
		local v = img.BestBanList[i]
		if v then
			if not img.BestBanImg[i] then
				img.BestBanImg[i] = {}
				img.BestBanImg[i].img =  d3d.CreateRect(img.BestBan.x-45*rate,img.bg.y+65*rate+70*rate*(i-1),90*rate,50*rate,0xffffffff,true,0)
				RoundedImage(img.BestBanImg[i].img,0,0xffffff99,2)
			end
			img.BestBanImg[i].img.textureId = GetTextureId2(v.name)
			if IsMouseOnButton(img.BestBanImg[i].img) then
				img.BestBanImg[i].img.color = 0xff2525ff
			else
				img.BestBanImg[i].img.color = 0xffffffff
			end
		elseif img.BestBanImg[i] then
			img.BestBanImg[i].img.visible =false
			img.BestBanImg[i] = {}
		end
	end

end

function SafeCall(heroName,heroID,v,i,yy,localplayer,allPlayers)
		--Y_POSIITON
	img[i].icon.y = yy-6*rate
	img[i].icon_color.y = img[i].icon.y
	img[i].nick.y = yy
	img[i].location.y = img[i].icon.y + 2
	img[i].location2.y = img[i].icon.y
	img[i].rating.y = yy-2*rate
	img[i].gamse.y = img[i].icon.y+1
	img[i].gamse_wr.y = img[i].icon.y+14*rate
	img[i].hero.y = img[i].icon.y+1
	img[i].hero_game.y = img[i].icon.y+1*rate
	img[i].hero_win.y =img[i].icon.y+14*rate
	img[i].rect.y = img[i].icon.y
	for z = 1,7 do
		img[i].last[z].icons.y = img[i].icon.y+1					
		img[i].last[z].kill.y = img[i].icon.y+22*rate
		img[i].last[z].dead.y = img[i].icon.y+22*rate
		--img[i].last[z].assist.y = img[i].icon.y+23*rate
	end
	for z = 1,3 do
		img[i].most[z].icons.y = img[i].icon.y+1
		img[i].most[z].games.y = img[i].icon.y+1
		img[i].most[z].win.y = img[i].icon.y+14*rate
	end
	if img[i].party[1] then
		for z = 1,3 do
			img[i].party[z].visible = false
		end
	end
	--Y_POSIITON
	if heroName then
		img[i].icon.textureId = GetTextureId2(heroName) img[i].icon.visible = true
	end
	if not info_tab.decode[i] then
		info_tab.base[i] = {}
		info_tab.decode[i] = {}
	end
	local infos = v:GetPlayerInfo()
	DecodeData(i,infos)
	local info = info_tab.decode[i]

	--= Current Hero
	if info.heroes then
		if heroID and img[i].hero.textureId == 0 and info.heroes and #info.heroes > 3 then
			for l,z in ipairs(info.heroes) do
				if tonumber(z["hero_id"]) and  tonumber(z["hero_id"]) == heroID then
					img[i].hero.textureId = GetTextureId2(FindHero(tonumber(z["hero_id"])),true)  img[i].hero.visible = true
					img[i].hero_game.text = tostring(z["games"]) img[i].hero_game.visible = true
					local wr = math.ceil(z["win"] / z["games"] * 100)
					if z["win"] == 0 and z["games"] == 0 then
						wr = 0
					end
					img[i].hero_win.text = tostring(wr).."%" img[i].hero_win.visible = true
					WrColor(wr,img[i].hero_win)
					break
				end
			end
		end
	end

	--= Win / Lose	
	if info.wl and info.wl["lose"] then
		local playing = tostring(info.wl["lose"])+tostring(info.wl["win"])+1
		local wins = math.floor(info.wl["win"]/playing*100)
		img[i].gamse.text = tostring(playing-1)
		img[i].gamse_wr.text = tostring(wins.."%")
		WrColor(wins,img[i].gamse_wr)
	end

	img[i].icon_color.color = players_color[i+1] or players_color[1]

	--= Last game					
	local match_data = info.matches--(auto_odota and (info.hidden or info.matches)) or (not auto_odota and (info.matches or info.hidden))
	if match_data and not match_data["error"] then
		for z = 1, 7 do
			local mathes = match_data[z]
			if mathes and mathes["hero_id"] and tonumber(mathes["hero_id"]) then
				img[i].last[z].icons.color = 0xFFFFFFFF
				img[i].last[z].icons.textureId = GetTextureId2(FindHero(mathes["hero_id"]))
				if auto_dotabuff then
					if IsMouseOnButton(img[i].last[z].icons) and mathes["match_id"] then
						if select_match_id>dota.GetTick() then
							os.execute("start https://www.dotabuff.com/matches/"..mathes["match_id"])
						end
						img[i].last[z].icons.color = 0x999999ff
					end
				end
				img[i].last[z].icons.border = IsWin(mathes) and 0x009900ff or 0xff0000ff
				local sum = IsPeforamnce(mathes)
				img[i].last[z].dead.w = math.min(sum*4.1,39*rate)
				img[i].last[z].kill.visible, img[i].last[z].dead.visible = true,true
			else
				img[i].last[z].kill.visible, img[i].last[z].dead.visible = false,false
				img[i].last[z].icons.color = 0xffffffaa
				img[i].last[z].icons.border = 0x000000aa
				img[i].last[z].icons.textureId = GetTextureId2("npc_dota_hero_default")
			end
		end

		--= Ban Analize
		if localplayer and not localplayer:IsTeamEnt(v) and not img[i].bestHero and not info.hidden and dota.GetGameState()~=Enum.GAME_STATE_PLAYER_DRAFT then
			img[i].bestHero = {}
			for z = 1,5 do
				local mathes = match_data[z]
				if mathes and mathes["hero_id"] and tonumber(mathes["hero_id"]) then
					local heroN = FindHero(mathes["hero_id"])
					if not img[i].bestHero[heroN] then
						img[i].bestHero[heroN] = 1
					end
					if IsWin(mathes) then
						img[i].bestHero[heroN] = img[i].bestHero[heroN] + 1
					end
					if heroN == "npc_dota_hero_meepo" or heroN == "npc_dota_hero_huskar" or heroN == "npc_dota_hero_broodmother" then
						img[i].bestHero[heroN] = img[i].bestHero[heroN] + 1
					end
					if IsPeforamnce(mathes)>9 then
						img[i].bestHero[heroN] = img[i].bestHero[heroN] + 1
					end
				end
			end
			local max = 0
			local banName
			for z,x in pairs(img[i].bestHero) do
				if x>max then
					max = x
					banName = z
				end
			end
			if banName then
				img.BestBanList[#img.BestBanList+1] = {name=banName,impact=max}
				table.sort(img.BestBanList,function(a,b) return a.impact>b.impact end)
			end
		end
	end

	--= Best				
	local best = info.heroes
	if not best or best["error"] or not best[1] or best[1]["games"] == 0 then
		best = info.best
	end
	if best then
		for z = 1,3 do
			local mathes = best[z]
			if mathes and mathes["hero_id"] and tonumber(mathes["hero_id"]) then
				img[i].most[z].icons.textureId = GetTextureId2(FindHero(tonumber(mathes["hero_id"])),true)
				img[i].most[z].games.text = tostring(mathes["games"] or "") img[i].most[z].games.visible = true
				img[i].most[z].win.text = IsWinProcent(mathes).."%" img[i].most[z].win.visible = true
				WrColor(tonumber(IsWinProcent(mathes)),img[i].most[z].win)
			else
				img[i].most[z].icons.textureId = GetTextureId2("panorama/images/hero_selection/unknown_hero_icon_png.vtex_c")
			end
		end
	end

	if blocked[i] then
		return
	end

	local fix_role = dota.PlayerResource.GetInstance():GetLaneSelectionFlag(i)
	img[i].rating.text = GetRoleNumber(fix_role)

	--= Party
	local p_info = infos.partyId

	if p_info~="" then

		local edx = v:GetPlayerId()

		local valid_ = {}
		for z,x in ipairs(allPlayers) do
			if x and x:GetPlayerId()~=edx and img[x:GetPlayerId()] then
				local info = x:GetPlayerInfo()
				if info and info.partyId ~= "" and info.partyId == p_info then
					valid_[#valid_+1] =x
				end
			end
		end

		for z,x in ipairs(valid_) do
			local ch = x:GetPlayerId()
			if not img[i].party[1] then
				img[i].party[1] = d3d.CreateRect(img[i].icon.x-10*rate ,img[i].icon.y+img[i].icon.h/3,  10*rate,1,0xffffffff,true,0)
				img[i].party[2] = d3d.CreateRect(img[ch].icon.x-10*rate,img[ch].icon.y+img[ch].icon.h/3,10*rate,1,0xffffffff,true,0)
				img[i].party[3] = DrawLine(img[i].party[1].x,img[i].party[1].y,img[i].party[2].x,img[i].party[2].y,0xffffffff)
			end

			img[i].party[1].visible = true
			img[i].party[2].visible = true
			img[i].party[3].visible = true

			img[i].party[1].x = img[i].icon.x-10*rate
			img[i].party[1].y = img[i].icon.y+img[i].icon.h/2

			img[i].party[2].x = img[ch].icon.x-10*rate
			img[i].party[2].y = img[ch].icon.y+img[ch].icon.h/2

			img[i].party[3].x0 = img[i].party[1].x
			img[i].party[3].y0 = img[i].party[1].y
			img[i].party[3].x1 = img[i].party[2].x
			img[i].party[3].y1 = img[i].party[2].y
		end
	end
	--= Tier and Lane	
	local fix_tier = dota.PlayerResource2.GetInstance():GetRankTier(i)
	if GetRankImage(fix_tier) then
		img[i].location.textureId = d3d.GetTextureId(GetRankImage(fix_tier))
		img[i].location2.textureId = d3d.GetTextureId(GetRankImage(fix_tier,true))
		img[i].location.visible = true
		img[i].location2.visible = true
		img[i].location.color = 0xffffffff
		img[i].location2.color = 0xffffffff
	else
		img[i].location.visible = false
		img[i].location2.visible = false
	end

end

function FixTeamIndex(tabs,team)
	if tabs[team] then
		tabs[team][#tabs[team]+1] = true
	elseif team > 10 then
		local re_team = #tabs[2] > #tabs[3] and 3 or 2
		tabs[re_team][#tabs[re_team]+1] = true
		return tabs,re_team
	end
	return tabs,team
end

--= SkinChanger
function ControleSkinCHange(game_state,localplayer)
	skins_button.visible = game_state < Enum.GAME_STATE_PRE_GAME and dota.PlayerResource.GetInstance():GetHeroId(localplayer:GetPlayerId()) > 0
	if skins_button.visible then
		skins_button.color = IsMouseOnButton(skins_button) and 0xFFEC97ff or 0x997B3499
	else
		if skins_button_close == Enum.GAME_STATE_STRATEGY_TIME and game_state > Enum.GAME_STATE_STRATEGY_TIME and dota.SkinChangerPanelIsOpen() then
			dota.ShowSkinPanel()
		end
	end
	skins_button_close = game_state
end

--= Other
function GetPlayerNormalName(v,DF13)
	local name = v:GetPlayerName():sub(1,16)
	local size = d3d.GetTextSize(DF13,v:GetPlayerName())
	if size.x > 289*rate then
		name = name:sub(1,14)
	end
	return name
end

function Dotabuff()
	local index = 0
	if dota.GetGameState()>Enum.GAME_STATE_INIT and dota.GetLocalPlayer() then
		index = dota.GetLocalPlayer():GetTeamIndex() or 0
	end
	local allPlayers = dota.FindEntities(dota.kDotaPlayer)
	if index==2 then
		table.sort( allPlayers, function (a,b) return a:GetTeamIndex() > b:GetTeamIndex() end)
	else
		table.sort( allPlayers, function (a,b) return a:GetTeamIndex() < b:GetTeamIndex() end)
	end
	for z,v in ipairs(allPlayers) do
		local pinfo = v:GetPlayerInfo()
		if pinfo then
			pinfo:SetPlayInfoState(true)
			--v:SendHiddenInfo()
		end
	end
end
function Dotabuff_OFF()
	local allPlayers = dota.FindEntities(dota.kDotaPlayer)
	for z,v in ipairs(allPlayers) do
		local pinfo = v:GetPlayerInfo()
		if pinfo then
			pinfo:SetPlayInfoState(false)
		end
	end
end
function GetPlayersCount(playerIDs,team,temp)

	if dota.GetGameState() == Enum.GAME_STATE_PLAYER_DRAFT then
		local start = team == 2 and 0 or 5
		for i = start,start+5 do
			if not temp[i] then
				temp[i] = true
				return i,temp
			end
		end
		return 9,temp
	end

	local num = 0
	local slot = dota.PlayerResource.GetInstance():GetTeamSlot(playerIDs)
	if team ~= 2 then
		num = slot+5
	else
		num = slot
	end
	if math.abs(num) < 10 and slot>-1 and slot<20 then
		return num
	else
		local cnt = 0
		for i,v in ipairs(dota.FindEntities(dota.kDotaPlayer)) do
			if v:IsTeam(team) then
				if v:GetPlayerId() < playerIDs then
					cnt = cnt + 1
				end
			end
		end
		if team == 2 then
			return cnt
		elseif team == 3 then
			return cnt + 5
		else
			return cnt + 1 + team
		end
	end
end
function IsWinProcent(mathes)
	if mathes["games"] then
		if tonumber(mathes["games"]) == 0 then
			return 0
		end
		return tostring(math.ceil(mathes["win"] / mathes["games"] * 100))
	else
		return tostring((math.floor(mathes["win"]*100)))
	end
end
function IsPeforamnce(mathes)
	if mathes["perf"] then
		return mathes["perf"] * 4 + 1
	else
		return (mathes["kills"]+mathes["assists"])/mathes["deaths"]
	end
end
function IsWin(mathes)
	if mathes["win"] then
		return mathes["win"]==1
	else
		return (mathes["player_slot"] < 5 and mathes["radiant_win"] or mathes["player_slot"] > 5 and not mathes["radiant_win"])
	end
end
function WrColor(wr,text)
	if wr == 0 then
		text.color = 0xffffffff
	elseif wr > 55 then
		text.color = 0x25ff25ff
	elseif wr<45 then
		text.color = 0xff2525ff
	else
		text.color = 0xffffffff
	end
end
function DecodeData(i,infos)
	if not info_tab.decode[i].wl then
		if not info_tab.base[i].wl or #info_tab.base[i].wl < 8 then
			info_tab.base[i].wl = infos.wl
		else
			info_tab.decode[i].wl = JSONs:decode(info_tab.base[i].wl)
			if not info_tab.decode[i].wl["win"] then
				info_tab.base[i].wl = nil
				info_tab.decode[i].wl = nil
			end
		end
	end
	for z,data in ipairs({"heroes","matches","hidden","best"}) do 
		if not info_tab.decode[i][data] and (data ~= "hidden" or infos.hidden) then
			if not info_tab.base[i][data] or #info_tab.base[i][data]== 0 then
				info_tab.base[i][data]= infos[data]
			else
				info_tab.decode[i][data] = JSONs:decode(info_tab.base[i][data])
				if info_tab.decode[i][data]["error"] then
					info_tab.base[i][data]= nil
					info_tab.decode[i][data] = nil
				end
			end
		end
	end
end

function SaveToNumber(x)
	if pcall(function(val) return val and tonumber(val) end,x) then
		return x and tonumber(x)
	end
	return false
end

function GetRankImage(num,start)
	local value = SaveToNumber(num)
	if not value or value < 1 or value>99 then
		return
	end
	if not start then
		local img = math.floor(value / 10)
		img = math.max(img,0)
		img = math.min(img,8)
		return "panorama/images/rank_tier_icons/rank"..img.."_psd.vtex_c"
	else
		local img = value%10
		img = math.max(img,1)
		img = math.min(img,7)
		return "panorama/images/rank_tier_icons/pip"..img.."_psd.vtex_c"
	end
end
function GetRoleNumber(role)
	local value = SaveToNumber(role)
	if not value or value == 0 then
		return ""
	end

	local rolesNames = {}
	rolesNames[16] = "5";
    rolesNames[8] = "4";
    rolesNames[2] = "3";
    rolesNames[4] = "2";
    rolesNames[1] = "1";
	return rolesNames[value] or ""
end

--= Show Role Top Panel
local function GetRoleText(role)
	local saverole = SaveToNumber(role)
	if not saverole or saverole == 0 then
		return ""
	end
	local rolesNames = {}
	rolesNames[16] = "DOTA_TopBar_LaneSelectionHardSupport";
    rolesNames[8] = "DOTA_TopBar_LaneSelectionSupport";
    rolesNames[2] = "DOTA_TopBar_LaneSelectionOfflane";
    rolesNames[4] = "DOTA_TopBar_LaneSelectionMidlane";
    rolesNames[1] = "DOTA_TopBar_LaneSelectionSafelane";
	if rolesNames[saverole] then
		return dota.Localize(rolesNames[saverole])
	else
		return ""
	end
end

function ShowRole()

	if menu and dota.IsExistPlayer() then

		if (dota.GetGameState() ~= Enum.GAME_STATE_HERO_SELECTION and dota.GetGameState() ~= Enum.GAME_STATE_STRATEGY_TIME) or not auto_odota then
			if top_role.init then
				for i = -20, 20 do
					if IsGoodPlayerId(i) then
						top_role[i] = DestroyImg(top_role[i])
					end
				end
				top_role = {}
			end
			return
		end

		local player = dota.GetLocalPlayer()

		if top_role.init or not player then
			return
		end

		top_role.init  = true

		local Monitor = {
			[233] = {offset = 160, 	step = 105},
			[177] = {offset = 160,  step = 103},
			[166] = {offset = 185, 	step = 103},
			[160] = {offset = 180, 	step = 104},
			[156] = {offset = 180, 	step = 103},
			[133] = {offset = 145, 	step = 86},
			[125] = {offset = 140, 	step = 79},
		}
		
		local ratio = math.min(233, math.floor(screen.x/screen.y*100))
		local curMonitor = Monitor[ratio] or Monitor[177]
		local resurs = dota.PlayerResource.GetInstance()

		function GetPanelPos(v,curMonitor)
			local index = resurs:GetTeamSlot(v:GetPlayerId())
			local x
			if v:IsTeam(2) then
				x = screen.x / 2 - curMonitor.offset*rate_y - (4-index) * curMonitor.step*rate_y
			else
				x = screen.x / 2 + curMonitor.offset*rate_y + index * curMonitor.step*rate_y
			end
			return dota.Vector(math.floor(x), math.floor(screen.y * 0.1),0)
		end

		local allPlayers = dota.FindEntities(dota.kDotaPlayer)
		for i,v in ipairs(allPlayers) do
			local i = v:GetPlayerId()
			if IsGoodPlayerId(i) and not v:IsTeamEnt(player) then
				local team_pos = GetPanelPos(v,curMonitor)
				local fix_role = dota.PlayerResource.GetInstance():GetLaneSelectionFlag(i)
				top_role[i] = d3d.CreateText(team_pos.x,team_pos.y,0x7A8B9Bff,GetRoleText(fix_role),FONT11)
				top_role[i].center = true
			end
		end
	end

end


local trans_text = {
	russian =  {player="Игрок", matches="Матчи",  last_games="				Последние игры",most="Лучшие герои",current="Текущий",best_ban="Лучший Бан"},
	schinese = {player="玩家",matches="场次",	last_games="				最近对局",most="最多使用",current="当前使用",best_ban="禁用方案"},
	other =    {player="Player",matches="Matches",last_games="				Last Games",	  most="Most Played", current="Current",best_ban="Best Ban"},
}
local menu_text =  trans_text[lang] or trans_text["other"]

function DrawPanel()
	if not img.bg then
		local siez_x = 1170*rate
		local down_y = 125*rate_y
		img.bg = d3d.CreateRect((dota.GetScreenSize().x-siez_x)/2,down_y,siez_x,465*rate,0x000000cc,false,0)
		img.bg2 = d3d.CreateRect((dota.GetScreenSize().x-siez_x)/2+1,down_y+1,siez_x-2,img.bg.h-2,0xffffff50,true,0)
		img.bg3 = d3d.CreateRect(img.bg2.x+img.bg2.w-150*rate,img.bg2.y+2,down_y+25*rate,img.bg2.h-4,0x25000025,false,0)

		img.bg_close = d3d.CreateRect(img.bg.x+img.bg.w-30*rate,img.bg.y+4*rate,26*rate,26*rate,0xff2020ff,false,d3d.GetTextureId("NtUI/native/disconnect.png"))

		local HeaderColor = 0xFFFFFFFF
		local yy = img.bg.y-23*rate
		img.radiant = d3d.CreateText(img.bg.x+20*rate,yy+50*rate,0x00ff00ff,"Radiant",DF15)
		img.dire 	= d3d.CreateText(img.bg.x+20*rate,yy+246*rate,0xff0000ff,"Dire",DF15)
		img.player	= d3d.CreateText(img.bg.x+100*rate,yy+50*rate,HeaderColor,menu_text.player,DF15)

		img.radiantLine	= d3d.CreateRect(img.radiant.x,img.radiant.y+30*rate,2*rate,30*5*rate,0x00ff00ff,false,0)
		img.direLine	= d3d.CreateRect(img.dire.x,img.dire.y+30*rate,2*rate,30*5*rate,0xff0000ff,false,0)

		img.MMR	= d3d.CreateText(img.player.x+110*rate,img.player.y,			HeaderColor,"",DF15)
		img.games	= d3d.CreateText(img.MMR.x+90*rate,img.player.y,			HeaderColor,menu_text.matches,DF15) img.games.center = true
		img.lastGames = d3d.CreateText(img.games.x+180*rate,img.player.y,		HeaderColor,menu_text.last_games,DF15) img.lastGames.center = true
		img.mostPlayerd = d3d.CreateText(img.lastGames.x+350*rate,img.player.y,	HeaderColor,menu_text.most,DF15) img.mostPlayerd.center = true
		img.CurrentHero = d3d.CreateText(img.mostPlayerd.x+150*rate,img.player.y,HeaderColor,menu_text.current,DF15) img.CurrentHero.center = true
		img.BestBan = d3d.CreateText(img.CurrentHero.x+113*rate,img.player.y,	HeaderColor,menu_text.best_ban,DF15) img.BestBan.center = true
		img.BestBanList = {}
		img.BestBanImg = {}
		local text = "White line - Game Impact. By clicking on the hero icon - ban this hero."
		if lang == "russian" then
			text = "Белая полоска - Импакт в игре. По нажатию на иконку бана - герой забанится!"
		elseif lang == "schinese" then
			text = "白色线条 - 影响力. 点击英雄图标将禁止这个英雄"
		end
		local option = "Auto enable on pick stage"
		if lang == "russian" then
			option = "Авто включение на пике"
		elseif lang == "schinese" then
			option = "挑选阶段自动弹出"
		end
		local showenemy = "Show enemy role"
		if lang == "russian" then
			showenemy = "Показывать вражеские роли"
		elseif lang == "schinese" then
			showenemy = "显示敌方分路角色"
		end

		img.auto_draw = d3d.CreateRect(img.bg.x+18*rate,img.bg.y+img.bg.h-44*rate,16*rate,16*rate,0xffffffff,false,CBTexture(auto_stats))
		img.auto_draw_text = d3d.CreateText(img.auto_draw.x+img.auto_draw.w+5*rate,img.auto_draw.y,0xffffffff,option,DF14)

		img.auto_dotabuff = d3d.CreateRect(img.auto_draw.x+img.auto_draw.w+18*rate+d3d.GetTextSize(DF14,option).x,img.auto_draw.y,16*rate,16*rate,0xffffffff,false,CBTexture(auto_dotabuff))
		img.auto_dotabuff_text = d3d.CreateText(img.auto_dotabuff.x+img.auto_dotabuff.w+5*rate,img.auto_dotabuff.y,0xffffffff,"Dotabuff click",DF14)

		img.auto_odota = d3d.CreateRect(img.auto_dotabuff.x+img.auto_dotabuff.w+18*rate+d3d.GetTextSize(DF14,img.auto_dotabuff_text.text).x,img.auto_draw.y,16*rate,16*rate,0xffffffff,false,CBTexture(auto_odota))
		img.auto_odota_text = d3d.CreateText(img.auto_odota.x+img.auto_odota.w+5*rate,img.auto_odota.y,0xffffffff,showenemy,DF14)

		img.Help = d3d.CreateText(img.auto_draw.x,img.auto_draw.y+22*rate,0x999999ff,text,DF13)

		Dotabuff()
		return true
	end
end
function DestroyPanel()
	img = {}
	Dotabuff_OFF()
	collectgarbage("collect")
end


function OnKey(msg,code)
	if msg == 513 then --L_MOUSE

		if skins_button.visible and IsMouseOnButton(skins_button) then
			dota.ShowSkinPanel()
		end

		if IsMouseOnButton(menu) then
			if img.bg or not dota.IsHUDFlipped() or not dota.IsShopSearch() then
				if not DrawPanel() then
					DestroyPanel()
				end
				return true
			end
		elseif img.bg then
			for i = 1, 5 do
				if img.BestBanList[i] and img.BestBanImg and IsMouseOnButton(img.BestBanImg[i].img) then
					img.BestBanImg[i].img.border = 0xff2525ff
					dota.ExecuteCommand("dota_captain_ban_hero "..img.BestBanList[i].name)
					aaa("Ban "..img.BestBanList[i].name)
				end
			end
			if IsMouseOnButton(img.bg_close) then
				DestroyPanel()
				return true
			elseif IsMouseOnButton(img.auto_draw) then
				CBSwitch(img.auto_draw)
				auto_stats = CFG:Write("Statistic","AutoOpen",CBIsEnable(img.auto_draw))
				return true
			elseif IsMouseOnButton(img.auto_dotabuff) then
				CBSwitch(img.auto_dotabuff)
				auto_dotabuff = CFG:Write("Statistic","OpendDB",CBIsEnable(img.auto_dotabuff))
				return true
			elseif IsMouseOnButton(img.auto_odota) then
				CBSwitch(img.auto_odota)
				auto_odota = CFG:Write("Statistic","PriorityDB",CBIsEnable(img.auto_odota))
				return true
			end
			select_match_id = dota.GetTick()+100
		end
	end
end

function Disconnect(msg)
	local name = msg:GetName()

	if name== "player_connect_full" then
		FullConnect()
	elseif menu and name == "map_shutdown" or (name == "dota_match_done_client" and ObsByPass()) then
		img = {}
		menu = nil
		skins_button = nil
		if hook then hook = nil end
		if key then	key = nil end
		info_tab = {base={},decode={}}
		collectgarbage("collect")
	end
end

function FullConnect()
	if not player_connect_full then
		local state = dota.GetGameState()
		if (state== Enum.GAME_STATE_HERO_SELECTION or state == Enum.GAME_STATE_WAIT_FOR_PLAYERS_TO_LOAD) and dota.GetLocalPlayer() then
			if auto_stats then
				DrawPanel()
			else
				Dotabuff()
			end
			full = dota.GetTick()+8000
		end
		player_connect_full = true
	end
end

function Initialize()
	player_connect_full = false
	hook = dota.AddTickEvent(OnTick)
	key = dota.AddKeyEvent(OnKey)
	if dota.GetLocalPlayer() then
		dota.GetLocalPlayer():ClearInfoData()
		img = {}
	end
	if not disconnect then
		disconnect = dota.AddFireEventHook(Disconnect)
	end
	menu = d3d.CreateRect(4*rate_y,107*rate_y,22*rate_y,22*rate_y,0xffffffff,true,d3d.GetTextureId("NtUI/native/stats.png"))
	menu.visible = not dota.ObsByPass()
	skins_button = d3d.CreateRect(-1,menu.y+22*rate_y,32*rate_y,32*rate_y,0x997B34ff,true,d3d.GetTextureId("panorama/images/topbar/armory_icon_white_png.vtex_c"))
	skins_button.visible = dota.GetGameState() < Enum.GAME_STATE_PRE_GAME

	info_tab = {base={},decode={}}
	top_role = {init = false}
	collectgarbage("collect")
end
