-- NewSniper 21.08.2013 
-- look_at_you_ 

Global('PLAYERLIST_MAX_ROWS', 13) --см. конфиг
Global("ClassColor", true) --см. конфиг

local ShowHideBtn 			= nil 
local wtMainPanel			= nil
local wtPlayerList_Name 	= nil
local wtPlayerList_Level 	= nil
local wtPlayerList_Health 	= nil
local wtButtonSelector 		= nil
local wtTotHealth 			= nil
local wtPlayerList_Icon 	= nil
local wtStatus 				= nil

local wtPlayerList_Names		= {}
local wtPlayerList_Levels		= {}
local wtPlayerList_Healths		= {}
local wtButtonSelectors			= {}
local wtTotHealths				= {}
local wtTotHBGs					= {}
local wtPlayerList_Icons		= {}

local unitList					= {}
local unitCount					= 0
local PVP 					  	= false

-----
local function GetConfig( name )
	local cfg = userMods.GetGlobalConfigSection( common.GetAddonName() )
	if not name then return cfg end
	return cfg and cfg[ name ]
end
local function SetConfig( name, value )
	local cfg = userMods.GetGlobalConfigSection( common.GetAddonName() ) or {}
	if type( name ) == "table" then
		for i, v in pairs( name ) do cfg[ i ] = v end
	elseif name ~= nil then
		cfg[ name ] = value
	end
	userMods.SetGlobalConfigSection( common.GetAddonName(), cfg )
end
-----

function Timer()
	local detectedUnits = avatar.GetUnitList()
	local i = 1
	unitList  = {}
	
	for key, unitId in detectedUnits do
	
		if(PVP) then
		
			if unit.IsPlayer(unitId) and not object.IsDead(unitId) and not raid.IsPlayerInAvatarsRaid(object.GetName(unitId)) and not group.IsCreatureInGroup(unitId) then 
			
				if not unit.GetFaction( unitId ).isFriend or unit.IsEnemy( unitId ) then

					unitList[i]             = {}
					unitList[i].id          = unitId
					unitList[i].priority    = 1 
					
					unitList[i].priority	= unitList[i].priority + unit.GetLevel( unitId ) * 1000
					unitList[i].priority	= unitList[i].priority + ( 100 - ( unit.GetHealthPercentage(unitId) ) ) * 100
					
					i = i + 1
				end

			end
		
		else
				
			if not object.IsDead(unitId) and not unit.IsPlayer(unitId) and not unit.IsPet(unitId) and unit.IsEnemy( unitId ) then

				unitList[i]             = {}
				unitList[i].id          = unitId
				unitList[i].priority    = 1
				
				unitList[i].priority	= unitList[i].priority + unit.GetLevel( unitId ) * 100
				unitList[i].priority    = unitList[i].priority + (100 - ( unit.GetHealthPercentage( unitId ) ) ) * 100
				unitList[i].priority    = unitList[i].priority + unit.GetQuality( unitId )*100000
				i = i + 1
			
			end
		
		end
	
	end
	
	unitCount = i - 1
	detectedUnits = nil
	ClearPlayerList()
	
	if unitCount > 0 then
	
		CreatePlayerList()
		wtMainPanel:Show(true)
		
	else
	
		wtMainPanel:Show(false)
		
	end
	
end

function CreatePlayerList()

	table.sort(unitList, function(a, b) return a.priority > b.priority end)
	
	for i = 1, unitCount do
	
		CreatePlayerPanel(i)
		if i >= PLAYERLIST_MAX_ROWS then break end
		
	end
	
end

function CreatePlayerPanel(i)

	local unitId = unitList[i].id
	local place

	------------name		
	wtPlayerList_Names[i] = mainForm:CreateWidgetByDesc(wtPlayerList_Name:GetWidgetDesc())
	wtPlayerList_Names[i]:SetName("PlayerList_Name"..i)
	--Чтобы имя не заползало за панельку хп
	local tmpstr = object.GetName(unitId)
	
	if (common.GetWStringLength (tmpstr) > 23) then 
		wtPlayerList_Names[i]:SetVal("Name", common.TruncateWString( tmpstr, 26, 3, false ))
	else 
		wtPlayerList_Names[i]:SetVal("Name", tmpstr) 
	end 
	
	if unit.GetPvPFlagInfo(unitId).isOn then 
		if(unit.GetFaction( unitId ).isSame) then
			wtPlayerList_Names[i]:SetClassVal("class", "tip_green")
		else 
			wtPlayerList_Names[i]:SetClassVal("class", "tip_red")	
		end
	else 
		wtPlayerList_Names[i]:SetClassVal("class", "LogColorGold")
	end
	place = wtPlayerList_Names[i]:GetPlacementPlain()
	place.posY = 3+20 * i;
	wtPlayerList_Names[i]:SetPlacementPlain(place)
	wtMainPanel:AddChild(wtPlayerList_Names[i])
	wtPlayerList_Names[i]:Show(true)

-------------level
	wtPlayerList_Levels[i] = mainForm:CreateWidgetByDesc(wtPlayerList_Level:GetWidgetDesc())
	wtPlayerList_Levels[i]:SetName("PlayerList_Level"..i)
	wtPlayerList_Levels[i]:SetVal("Level", common.FormatInt(unit.GetLevel(unitId), "%d"))
	wtPlayerList_Levels[i]:SetClassVal("class", "tip_white") --NB
	place = wtPlayerList_Levels[i]:GetPlacementPlain()
	place.posY = 3+20 * i;
	wtPlayerList_Levels[i]:SetPlacementPlain(place)	
	wtMainPanel:AddChild(wtPlayerList_Levels[i])	
	wtPlayerList_Levels[i]:Show(true)

----------------health		
	wtPlayerList_Healths[i] = mainForm:CreateWidgetByDesc(wtPlayerList_Health:GetWidgetDesc())
	wtPlayerList_Healths[i]:SetName("PlayerList_Health"..i)
	local unitHP = unit.GetHealthPercentage(unitId)
	wtPlayerList_Healths[i]:SetVal("Health", common.FormatInt(unitHP, "%d"))
	if unitHP > 65 then
		wtPlayerList_Healths[i]:SetClassVal("class", "tip_green")
	elseif unitHP <= 65 and unitHP > 30 then
		wtPlayerList_Healths[i]:SetClassVal("class", "tip_yellow")
	elseif unitHP <= 30 then
		wtPlayerList_Healths[i]:SetClassVal("class", "tip_red")
	end
	place = wtPlayerList_Healths[i]:GetPlacementPlain()
	place.posY = 3+20 * i;
	wtPlayerList_Healths[i]:SetPlacementPlain(place)
	wtMainPanel:AddChild(wtPlayerList_Healths[i])
	wtPlayerList_Healths[i]:Show(true) 

-----------------button	
	wtButtonSelectors[i] = mainForm:CreateWidgetByDesc(wtButtonSelector:GetWidgetDesc())
	wtButtonSelectors[i]:SetName("ButtonSelector_"..i)
	place = wtButtonSelectors[i]:GetPlacementPlain()
	place.posY = 20 * i;
	wtButtonSelectors[i]:SetPlacementPlain(place)
	wtMainPanel:AddChild(wtButtonSelectors[i])
	wtButtonSelectors[i]:Show(true) 
	
---------------background		
	local Percentage = unit.GetHealthPercentage(unitId)
	wtTotHealths[i] = mainForm:CreateWidgetByDesc(wtTotHealth:GetWidgetDesc())
	if Percentage ~= nil then
	place = wtTotHealths[i]:GetPlacementPlain()
	place.posY = 20 * i;
	place.sizeX = math.ceil( 175 * Percentage / 100 )
	wtTotHealths[i]:SetPlacementPlain(place)
	end
	if ClassColor and PVP then
	wtTotHealths[i]:SetBackgroundColor( GetUnitClassColor(unitId) )
	else
	wtTotHealths[i]:SetBackgroundColor( {r = 1.00; g = 0; b = 0; a = 0.5} )
	end
	wtMainPanel:AddChild(wtTotHealths[i])
	wtTotHealths[i]:Show(true)
	
	--wtTotHBGs
	wtTotHBGs[i] = mainForm:CreateWidgetByDesc(wtTotHealth:GetWidgetDesc())
	place = wtTotHBGs[i]:GetPlacementPlain()
	place.posY = 20 * i;
	place.sizeX = 175;
	wtTotHBGs[i]:SetPlacementPlain(place)
	wtTotHBGs[i]:SetBackgroundColor( {r = 80/255; g = 80/255; b = 80/255; a = 0.5} )
	wtTotHBGs[i]:SetPriority((wtTotHBGs[i]:GetPriority())-1)
	wtMainPanel:AddChild(wtTotHBGs[i])
	wtTotHBGs[i]:Show(true)
	
-------------------wtPlayerList_Icons
	wtPlayerList_Icons[i] = mainForm:CreateWidgetByDesc(wtPlayerList_Icon:GetWidgetDesc())
	place = wtPlayerList_Icons[i]:GetPlacementPlain()
	place.posY = 20 * i;
	wtPlayerList_Icons[i]:SetPlacementPlain(place)
	
	if PVP then
	
	wtPlayerList_Icons[i]:SetBackgroundTexture(GetUnitClassIcon( unitId ))
	wtPlayerList_Icons[i]:SetBackgroundColor( GetUnitClassColor(unitId) )
	
	else
	
	wtPlayerList_Icons[i]:SetBackgroundTexture( GetUnitQualityIcon( unit.GetQuality( unitId ) ) )	
	
	end
	
	wtMainPanel:AddChild(wtPlayerList_Icons[i])
	wtPlayerList_Icons[i]:Show(true)
	-------------------
	place = wtMainPanel:GetPlacementPlain()
	place.sizeY = 20 * i +36;
	wtMainPanel:SetPlacementPlain(place)		

end


function ClearPlayerList()
	if wtPlayerList_Names then
		for i, w in wtPlayerList_Names do
			if wtPlayerList_Names[i] then 
				wtPlayerList_Names[i]:DestroyWidget()
			end
			if wtPlayerList_Levels[i] then
				wtPlayerList_Levels[i]:DestroyWidget()
			end
			if wtPlayerList_Healths[i] then
				wtPlayerList_Healths[i]:DestroyWidget()
			end
			if wtTotHealths[i] then
				wtTotHealths[i]:DestroyWidget()
			end
			if wtButtonSelectors[i] then
				wtButtonSelectors[i]:DestroyWidget()
			end
			if wtPlayerList_Icons[i] then
				wtPlayerList_Icons[i]:DestroyWidget()
			end
			if wtTotHBGs[i] then
				wtTotHBGs[i]:DestroyWidget()
			end
		end
	end
end

function SelectTarget(params)
	local senderIndex = tonumber(string.sub(params.sender, string.len("ButtonSelector_") + 1))
	if senderIndex then	avatar.SelectTarget(unitList[senderIndex].id) end
end

function SetMode(params)

	if DnD:IsDragging() then return end 
	
	if PVP then 

		PVP=false 
		wtStatus:SetVal( "value", userMods.ToWString( "M" ) )
		
	elseif not PVP then

		PVP=true 
		wtStatus:SetVal( "value", userMods.ToWString( "P" ) )
		
	end
	
	SetConfig( "PVP", PVP )
	
	Timer() --Можно убрать. Делалось ради быстрой реакции списка при смене режима.
	
end

function Init()
	--RegisterEvent/Reaction
	common.RegisterReactionHandler( SetMode, "ShowHideBtnReaction" ) 
	common.RegisterReactionHandler( SelectTarget, "SelectTarget" )
	common.RegisterEventHandler( Timer, "EVENT_SECOND_TIMER" )

	--widget
	wtMainPanel         = mainForm:GetChildChecked("MainPanel", false)
	wtPlayerList_Name   = wtMainPanel:GetChildChecked("PlayerList_Name", false)
	wtPlayerList_Level  = wtMainPanel:GetChildChecked("PlayerList_Level", false)
	wtPlayerList_Health = wtMainPanel:GetChildChecked("PlayerList_Health", false)
	wtButtonSelector    = wtMainPanel:GetChildChecked("ButtonSelector", false)
	wtTotHealth 		= wtMainPanel:GetChildChecked("TotHealth", false )
	wtPlayerList_Icon	= wtMainPanel:GetChildChecked("PlayerList_Icon", false)
	
	ShowHideBtn			= mainForm:GetChildChecked("ShowHideBtn", false)
	wtStatus 			= ShowHideBtn:GetChildChecked("Status", false )
	
	--Drag&Drop
	DnD:Init(wtMainPanel,wtMainPanel, true, true, {-8,-8,-8,-8}, nil )
	DnD:Init(ShowHideBtn,ShowHideBtn, true, true, {1,1,1,1}, nil )
	
	--config
	PVP = GetConfig("PVP")
	if PVP then 
	
		wtStatus:SetVal( "value", userMods.ToWString( "P" ) ) 
		
	else 
	
		wtStatus:SetVal( "value", userMods.ToWString( "M" ) ) 
	
	end
	
	-- from old NewSniper
	if GetConfig("SHBtn") ~= nil then SetConfig("SHBtn", nil) end
	
end

Init()