--------------------------------------------------------------------------------
-- GLOBALS
--------------------------------------------------------------------------------

Global( "wtMainPanel", nil )
Global( "wtLastUnlocked", nil )
Global( "wtSecondaryPanel", nil )
Global( "wtGroupPanel", nil )
Global( "wtGUnlocked", nil )
Global( "wtShowHideBtn", {} )

Global( "wtCloseBtn", {} )

Global( "wtSectorList", nil )
Global( "SectorValues", nil )
Global( "wtPlayerProgress", nil )

Global( "onEvent", {} )
Global( "onReaction", {} )

Global( "revision", 27.2 )

Global( "enable", 0 )
Global( "ver", 0)




-- Sector Names
function getGameSectorName(l,s)
	local astralAddons = astral.GetAddons()
	local sectors = astral.GetAddonSectors(astralAddons[l])
	local secInfo = astral.GetSectorInfo(sectors[s])
	local sectorName
	if secInfo and secInfo.name then
		sectorName = secInfo.name
	end
	if ver == 0 then return string.sub(userMods.FromWString(sectorName),7,-8)
	elseif ver == 1 then return userMods.FromWString(sectorName)
	end
end

function getSectorNumber(n)
	local SectorNumber = {
		[1]  = 0,
		[2]  = 2,
		[3]  = 5,
		[4]  = 7,
		[5]  = 4,
		[6]  = 1,
		[7]  = 10,
		[8]  = 8,
		[9]  = 11,
		[10] = 15,
		[11] = 16,
		[12] = 17,
		[13] = 18,			
		[14] = 21,
		[15] = 16,
		[16] = 12,
		[17] = 23,
		[18] = 3,
		[19] = 22,
		[20] = 24,
		[21] = 25,
		[22] = 27,
		[23] = 14,
		[24] = 9,
		[25] = 20,
		[26] = 28,
		[27] = 26,
		[28] = 13,
		[29] = 29,
		[30] = 19,
		[31] = 30,
		[32] = 31,
		[33] = 32,
		[34] = 33,
		[35] = 34,	
	
	}
	return SectorNumber[n]
end

function GetSectorName(v,t)
	local SectorName = {
		["long"] = {	
			[0]  = GetTextLocalized("Not Friendly"),
			[1]  = getGameSectorName(1,getSectorNumber(1)),
			[2]  = getGameSectorName(1,getSectorNumber(2)),
			[3]  = getGameSectorName(1,getSectorNumber(3)),
			[4]  = getGameSectorName(1,getSectorNumber(4)),
			[5]  = getGameSectorName(1,getSectorNumber(5)),
			[6]  = getGameSectorName(1,getSectorNumber(6)),
			[7]  = getGameSectorName(1,getSectorNumber(7)),
			[8]  = GetTextLocalized("A7"),
			[9]  = getGameSectorName(1,getSectorNumber(8)),
			[10] = getGameSectorName(1,getSectorNumber(9)),
			[11] = getGameSectorName(1,getSectorNumber(10)),
			[12] = getGameSectorName(1,getSectorNumber(11)),
			[13] = getGameSectorName(1,getSectorNumber(12)),
			[14] = getGameSectorName(1,getSectorNumber(13)),
			[15] = getGameSectorName(1,getSectorNumber(14)),
			[16] = getGameSectorName(1,getSectorNumber(15)),
			[17] = getGameSectorName(1,getSectorNumber(16)),
			[18] = getGameSectorName(1,getSectorNumber(17)),
			[19] = getGameSectorName(1,getSectorNumber(18)),
			[20] = getGameSectorName(1,getSectorNumber(19)),
			[21] = getGameSectorName(1,getSectorNumber(20)),
			[22] = getGameSectorName(1,getSectorNumber(21)),
			[23] = getGameSectorName(1,getSectorNumber(22)),
			[24] = getGameSectorName(1,getSectorNumber(23)),
			[25] = getGameSectorName(1,getSectorNumber(24)),
			[26] = getGameSectorName(1,getSectorNumber(25)),
			[27] = getGameSectorName(1,getSectorNumber(26)),
			[28] = getGameSectorName(1,getSectorNumber(27)),
			[29] = getGameSectorName(1,getSectorNumber(28)),
			[30] = getGameSectorName(1,getSectorNumber(29)),
			[31] = getGameSectorName(1,getSectorNumber(30)),
			[32] = getGameSectorName(1,getSectorNumber(31)),
			[33] = getGameSectorName(1,getSectorNumber(32)),
			[34] = getGameSectorName(1,getSectorNumber(33)),
			[35] = getGameSectorName(1,getSectorNumber(34)),
			[36] = getGameSectorName(1,getSectorNumber(35)),
			[37] = GetTextLocalized("A8"),
			[38] = GetTextLocalized("A9"),
			[39] = GetTextLocalized("A10"),
			[40] = GetTextLocalized("A11"),
			},
		["number"] = {
			[0]  = GetTextLocalized("Not Friendly"),
			[1]  = "S1",
			[2]  = "S2",
			[3]  = "S3",
			[4]  = "S4",
			[5]  = "S5",
			[6]  = "S6",
			[7]  = "S7",
			[8]  = "A7",
			[9]  = "S8",
			[10]  = "S9",
			[11] = "S10",
			[12] = "S11",
			[13] = "S12",
			[14] = "S13",
			[15] = "S14",
			[16] = "S15",
			[17] = "S16",
			[18] = "S17",
			[19] = "S18",
			[20] = "S19",
			[21] = "S20",
			[22] = "S21",
			[23] = "S22",
			[24] = "S23",
			[25] = "S24",
			[26] = "S25",
			[27] = "S26",
			[28] = "S27",
			[29] = "S28",
			[30] = "S29",
			[31] = "S30",
			[32] = "S31",
			[33] = "S32",
			[34] = "S33",
			[35] = "S34",
			[36] = "S35",
			[37] = "A8",
			[38] = "A9",
			[39] = "A10",
			[40] = "A11",
			},
	}
	return SectorName[t][v]
end


function getGameSectorValue(l,s)
	local astralAddons = astral.GetAddons()
	local astralAddonSectors = astral.GetAddonSectors(astralAddons[l])
	local secInfo = astral.GetSectorInfo(astralAddonSectors[s])
	local unlockLevel
	if secInfo and secInfo.astralLevel then 
		unlockLevel = secInfo.astralLevel 
	end
	return unlockLevel
end
function GetSectorValue(v)

	SectorValues = {
		
			[0]  = 0,                --Not Friendly
			[1]  = 4.3000001907349,  --S1
			[2]  = 4.4499998092651,  --S2
			[3]  = 4.4499998092651,  --S3
			[4]  = 4.75,             --S4
			[5]  = 4.9000000953674,  --S5
			[6]  = 5,                --S6
			[7]  = 5.25,             --S7
			[8]  = 5.5,              --A7
			[9]  = 5.5999999046326,	 --S8
			[10]  = 5.6500000953674,  --S9
			[11] = 5.6999998092651,  --S10
			[12] = 5.8000001907349,  --S11
			[13] = 5.8499999046326,  --S12
			[14] = 6,                --S13
			[15] = 6.1999998092651,  --S14
			[16] = 6.3000001907349,  --S15  
			[17] = 6.5,  --S16  
			[18] = 6.75,             --S17
			[19] = 6.8000001907349,  --S18
			[20] = 6.8499999046326,  --S19
			[21] = 6.8499999046327,  --S20
			[22] = 6.9000000953674,  --S21
			[23] = 7,                --S22
			[24] = 7.0699996948242,  --S23
			[25] = 7.0999999046326,  --S24
			[26] = 7.1199998855591,  --S25
			[27] = 7.25,             --S26
			[28] = 7.3000001907349,  --S27
			[29] = 7.3299999237061,  --S28
			[30] = 7.5199999809265,  --S29
			[31] = 7.539999961853,   --S30
			[32] = 7.5699996948242,  --S31
			[33] = 7.5999999046326,  --S32
			[34] = 7.75,             --S33
			[35] = 7.7799997329712,  --S34
			[36] = 7.8199996948242,  --S35
			[37] = getGameSectorValue(2,42),
			[38] = getGameSectorValue(2,5),
			[39] = getGameSectorValue(2,9),
			[40] = getGameSectorValue(2,62),
		
	}
	return SectorValues[v]
end


-- Return the progress of unlocking the next sector (expressed in %)
function GetPercentage(v,i)	 
	local x = GetSectorValue(i) 
	local y = GetSectorValue(i+1)
	local percentage = (v-x)/((y-x)/100)*10
	return math.floor(percentage)/10
end


function GetSectorIndex(v)
	local val = GetSectorValue
	local i = 0
	if v == val(0) then   -- Not Friendly
		i = 0
	end
	for j = 3, 39 do
		if v >= val(j) and v < val(j+1) then
			i = j
			if i == 20 then i = 21 end
			break
		end
		if v>=val(40) then
			i = 40
		end
	end
	return i
end



-- "EVENT_AVATAR_SECONDARY_TARGET_CHANGED"
-- "EVENT_AVATAR_PRIMARY_TARGET_CHANGED"

function OnEventTargetChanged()
	local targetId = avatar.GetTarget()
	if not targetId or not unit.IsPlayer( targetId ) or not unit.IsFriend( targetId) then
		wtMainPanel:Show( false )
		return
	end
	
	local unlock = astral.GetPlayerUnlockLevel(targetId)

	local WidgetText = GetTextLocalized("Error")
	local SectorIndex = GetSectorIndex(unlock)
	local Sector = GetSectorName(SectorIndex,"number")
	local NextSector = GetSectorName(SectorIndex+1,"number")
	local Percentage = GetPercentage(unlock,GetSectorIndex(unlock))
	local WidgetText = Sector.." ("..Percentage.."% "..GetTextLocalized("to").." "..NextSector..")"
	--common.LogInfo("", tostring(unlock).."  "..Sector.."  "..Percentage.."%" )
	
	if unlock == 0 then
		WidgetText = GetTextLocalized("Not Friendly")
	end
	if SectorIndex == 40 then
		WidgetText = GetTextLocalized("Full Unlock")
	end
	
	wtLastUnlocked:SetVal( "value", userMods.ToWString(WidgetText))
	wtMainPanel:Show( true )
end

-- Secondary Panel (Text Widget)
function FillSecondaryPanel()
	local unlock = astral.GetPlayerUnlockLevel(avatar.GetId())
	local WidgetText = GetTextLocalized("Error")
	local SectorIndex = GetSectorIndex(unlock)
	local Sector = GetSectorName(SectorIndex,"number")
	local NextSector = GetSectorName(SectorIndex+1,"number")
	local Percentage = GetPercentage(unlock,GetSectorIndex(unlock))
	Percentage = Percentage.."%"
	local WidgetText = Sector.." ("..Percentage.." "..GetTextLocalized("to").." "..NextSector..")"
	--wtLastUnlocked:SetVal( "value", userMods.ToWString(WidgetText))
	BuildSectorList(SectorIndex)
	local lastUnlocked = GetSectorName(SectorIndex,"long").." ("..GetSectorName(SectorIndex,"number")..")"
	local nextSector = GetSectorName(SectorIndex+1,"long").." ("..GetSectorName(SectorIndex+1,"number")..")"
	local value = Percentage--.." ("..unlock..")"  --temporary
	wtPlayerProgress:SetVal("lastUnlocked", userMods.ToWString(lastUnlocked))
	wtPlayerProgress:SetVal("nextSector", userMods.ToWString(nextSector))
	--wtPlayerProgress:SetVal("progress", userMods.ToWString(Progress))
	wtPlayerProgress:SetVal("progress", userMods.ToWString(value))   -- temporary
	wtPlayerProgress:SetVal("nextSectorShort", userMods.ToWString(NextSector))
	
end

-- Build the Sector List
function BuildSectorList(v)
	local TempSectorList1 = ""
	local TempSectorList2 = ""
	local TempSectorList3 = ""
	TempSectorList1 = GetSectorName(1,"number").." > "..GetSectorName(2,"number")
	for i=3, v-1 do
		TempSectorList1 = TempSectorList1.." > "..GetSectorName(i,"number")
	end
	TempSectorList1 = TempSectorList1.." > "
	TempSectorList2 = GetSectorName(v,"number")
	if v<40 then
		for i=v+1, 40 do
			TempSectorList3 = TempSectorList3.." > "..GetSectorName(i,"number")
		end
	end
	wtSectorList:SetVal("list1", userMods.ToWString(TempSectorList1))
	wtSectorList:SetVal("lastSector", userMods.ToWString(TempSectorList2))
	if v<40 then
		wtSectorList:SetVal("list2", userMods.ToWString(TempSectorList3))
	end
end


function GetGroupUnlock()
	if group.IsCreatureInGroup( avatar.GetId() ) and (not raid.IsExist() ) then
	local gsect = GetSectorName(GetSectorIndex(astral.GetGroupUnlockLevel()),"number")
	wtGUnlocked:SetVal("value", toWS(gsect))
	wtGroupPanel:Show(true)
	end
end

function GroupOver()
	wtGroupPanel:Show(false)
end

onEvent[ "EVENT_GROUP_APPEARED" ] =  function()
	GetGroupUnlock()
end

onEvent[ "EVENT_GROUP_DISAPPEARED" ] =  function()
	GroupOver()
end

onEvent[ "EVENT_RAID_DISAPPEARED" ] = function()
	GroupOver()
end

onEvent[ "EVENT_GROUP_MEMBER_ADDED" ] =  function(p)
	GetGroupUnlock()
end

onEvent[ "EVENT_GROUP_MEMBER_REMOVED" ] =  function(p)
	GetGroupUnlock()
end


	
--------------------------------------------------------------------------------

-- "SCRIPT_ADDON_INFO_REQUEST" - Send info about the addon to AddonManager
onEvent[ "SCRIPT_ADDON_INFO_REQUEST" ] = function( params )
	if params.target == common.GetAddonName() then
		userMods.SendEvent( "SCRIPT_ADDON_INFO_RESPONSE", {
			sender = params.target,
			desc = userMods.FromWString( userMods.ToWString("Information about astral Progress" )),
			showDNDButton = true,
			showHideButton = true,
			showSettingsButton = false,
		} )
	end
end

-- "SCRIPT_TOGGLE_VISIBILITY" - Hides the widgets when AddonManager sends this event 
onEvent[ "SCRIPT_TOGGLE_VISIBILITY" ] = function ( params )
	if params.target == common.GetAddonName() then
		if params.state then
			mainForm:Show( true)
		else
			mainForm:Show( false )
		end
	end
end


--Show/hide the text widget
onReaction[ "ShowHideBtnReaction" ] = function ( reaction )
if DnD:IsDragging() then return end
	if wtSecondaryPanel:IsVisible() then
		wtSecondaryPanel:Show( false )
	else
		wtSecondaryPanel:Show( true )
		FillSecondaryPanel()
	end
end


-- "U_EVENT_ADDON_MEM_USAGE_REQUEST" -- Sending memory usage info to "Addon Manager"
onEvent[ "U_EVENT_ADDON_MEM_USAGE_REQUEST" ] = function ( event )
	userMods.SendEvent( "U_EVENT_ADDON_MEM_USAGE_RESPONSE", { sender = common.GetAddonName(), memUsage = gcinfo() } )
end

-- "U_EVENT_TOGGLE_DND" -- Lock DnD from Addon Manager
onEvent[ "SCRIPT_TOGGLE_DND" ] = function( params )
	if params.target == common.GetAddonName() then
		DnD:Enable( wtShowHideBtn, params.state )
		DnD:Enable( wtMainPanel, params.state )
		
	end
end
-- Close Text Widget
onReaction[ "close" ] = function ( reaction )
	wtSecondaryPanel:Show( false )
end


onEvent[ "EVENT_UNKNOWN_SLASH_COMMAND" ] = function (p)
	local msg = userMods.FromWString(p.text)
	if msg == "/aiv" then
		LogToChat("Revision "..tostring(revision), "LogColorYellow", 18)
	end
end

-- Esc Reaction. Still testing
onReaction[ "esc_pressed"] = function ( params )
	if wtSecondaryPanel:IsVisible() then
		wtSecondaryPanel:Show(false)
	end
end

-- AOPanelMod Integration
onEvent [ "AOPANEL_START" ] = function( params )
	if avatar.IsExist() then
		local unlock = astral.GetPlayerUnlockLevel(avatar.GetId())
		local SectorIndex = GetSectorIndex(unlock)
		local Sector = GetSectorName(SectorIndex,"number")
		local SetVal = { val1 = userMods.ToWString(Sector), class1 = "Legendary" }
		local params = { header = SetVal, ptype = "button", size = 44 } 
		userMods.SendEvent( "AOPANEL_SEND_ADDON", { name = "AstralInfo", sysName = "AstralInfo", param = params } )
		wtShowHideBtn:Show(false)
	end
end

onEvent [ "AOPANEL_BUTTON_LEFT_CLICK" ] = function( params )
	if params.sender ~= "AstralInfo" then return end
	onReaction[ "ShowHideBtnReaction" ]()
end

onEvent [ "EVENT_ADDON_LOAD_STATE_CHANGED" ] = function( params )
	--LogToChat(params.name)
	if params.name == "UserAddon/AOPanelMod" and params.unloading then wtShowHideBtn:Show(true) end
end

onEvent [ "EVENT_PLAYER_ASTRAL_UNLOCK_CHANGED" ] = function ( params )
	local playerId = params.playerId
	if playerId == avatar.GetId() then 
		local unlock = astral.GetPlayerUnlockLevel(avatar.GetId())
		local SectorIndex = GetSectorIndex(unlock)
		local Sector = GetSectorName(SectorIndex,"number")
		local SetVal = { val1 = userMods.ToWString(Sector), class1 = "Legendary" }
		userMods.SendEvent( "AOPANEL_UPDATE_ADDON", { sysName = "AstralInfo", header = SetVal } )
	end
	GetGroupUnlock()
end

-- Register The Event Handlers
-- Call with onEvent[ "EVENT_NAME" ] = function( params )
function RegisterEventHandlers( handlers )
	for event, handler in handlers do
		common.RegisterEventHandler( handler, event )
	end
end

-- Register The Reaction Handlers
-- Call with onReaction[ "REACTION_NAME" ] = function( params )
function RegisterReactionHandlers( handlers )
	for event, handler in handlers do
		common.RegisterReactionHandler( handler, event )
	end
end

--------------------------------------------------------------------------------
-- INITIALIZATION
--------------------------------------------------------------------------------
function Init()
	
	RegisterEventHandlers( onEvent )
	RegisterReactionHandlers ( onReaction )
	
	common.RegisterEventHandler( OnEventTargetChanged, "EVENT_AVATAR_SECONDARY_TARGET_CHANGED" )
	common.RegisterEventHandler( OnEventTargetChanged, "EVENT_AVATAR_PRIMARY_TARGET_CHANGED" )
	
	
	wtMainPanel = mainForm:GetChildChecked( "MainPanel", false )           -- The bar under the target's plates
	wtGroupPanel = mainForm:GetChildChecked( "GroupPanel", false)          -- The bar for group unlock
	wtGUnlocked = wtGroupPanel:GetChildChecked( "LastUnlocked", false)
	wtLastUnlocked = wtMainPanel:GetChildChecked( "LastUnlocked", false )  
	wtSecondaryPanel = mainForm:GetChildChecked( "SecondaryPanel", false ) -- The text widget
	wtShowHideBtn = mainForm:GetChildChecked( "ShowHideBtn", false )       -- The button
	wtMainPanel:Show (false)
	wtCloseBtn = wtSecondaryPanel:GetChildChecked( "CloseBtn", false )
	wtSectorList = wtSecondaryPanel:GetChildChecked( "SectorList", false )
	wtPlayerProgress = wtSecondaryPanel:GetChildChecked( "PlayerProgress", false )
	
	local wtHeader = wtSecondaryPanel:GetChildChecked("Header", false)
	wtHeader:SetVal("header", toWS(GetTextLocalized("Header")))
	
	wtSectorList:SetVal("Sector List", toWS(GetTextLocalized("Sector List")))
	wtPlayerProgress:SetVal("Last Unlocked Sector", toWS(GetTextLocalized("Last Unlocked Sector")))
	wtPlayerProgress:SetVal("Next Unlockable Sector", toWS(GetTextLocalized("Next Unlockable Sector")))
	wtPlayerProgress:SetVal("Progress towards", toWS(GetTextLocalized("Progress towards")))
	
	wtCloseBtn:SetVal("button_label", toWS(GetTextLocalized("Close")))
	
	
	DnD:Init( wtMainPanel, wtMainPanel, true, false )
	DnD:Enable( wtMainPanel, true )
	
	DnD:Init( wtSecondaryPanel, wtSecondaryPanel, true, false )
	DnD:Enable( wtSecondaryPanel, true )
	wtSecondaryPanel:Show( false )
	
	DnD:Init( wtShowHideBtn, wtShowHideBtn, true, false )
	DnD:Enable( wtShowHideBtn, true )
	
	DnD:Init ( wtGroupPanel, wtGroupPanel, true, false)
	DnD:Enable( wtGroupPanel, true)
	wtGroupPanel:Show(false)
	
	
	if avatar.IsExist() and group.IsCreatureInGroup (avatar.GetId()) then GetGroupUnlock() end
	
	
	if avatar.IsExist() then
		OnEventTargetChanged()
		onEvent [ "AOPANEL_START" ]()
	end
	
end
--------------------------------------------------------------------------------
Init()
--------------------------------------------------------------------------------
