


GHU_MAPICONS = {}
GHU_MAPICONS.__index = GHU_MAPICONS;
GHU_MAPICONS.hooked ={};

local mapfiles = LibStub("LibMapData-1.0"); 

----Internal funcs
---need an update timer...
---borrowing some stuff from tomtom
local Minimap_OnEnter,Minimap_OnLeave,Minimap_OnUpdate,Minimap_OnClick,Minimap_OnEvent
local Arrow_OnUpdate
local World_OnEnter,World_OnLeave,World_OnClick,World_OnEvent

local minimapP = Minimap
local pool = {}
local all_points = {}

local square_half = math.sqrt(0.5)
local rad_135 = math.rad(135)


local ghstPOI = "Interface\\Minimap\\POIIcons" -- POI Icons file
local ghstOBJI = "Interface\Minimap\OBJECTICONS"--Obj/minimap blip icon file
local ghstQicon = "Interface\\GossipFrame\\AvailableQuestIcon"--quest icons.
local ghstDQicon = "Interface\\GossipFrame\\DailyQuestIcon"
local ghstQNCicon = "Interface\\GossipFrame\\IncompleteQuestIcon"
local ghstQCicon = "Interface\\GossipFrame\\ActiveQuestIcon"
GHU_MAPICONS.iconlist = {
--POI
poi = {
minegrey = 1,
minered = 2,
mineblue = 3,
gyatkblue = 4,--graveyard under assult by blue
town = 5,
city = 6,
flagexcla = 7, -- red flag with ! in center
gravestone = 8,
toweratkblue = 9,
towerred = 10,
towerblue = 11,
toweratkred = 12,
gyred = 13,
gyatkred = 14,
gyblue = 15,
gminegrey = 16,
gmineatkblue = 17,
gmineblue = 18,
gmineatkred = 19,
gminered = 20,
millgrey = 21,
millatkblue = 22,
millblue = 23,
millatkred = 24,
millred = 25,

},
--colors can be used to show an area under attack (for future addons) or represent other events
colors = {
["red"] = {1,0.0,0.0},--underattack color
["yellow"]={1,1,0},
["blue"]={0,0,1},
--more later?

}

--Objects

}

local function GHrotateArrow(self,icon)
	if self.disabled then return end

	local dist,angle = mapfiles:DistanceAndDirection(GetMapInfo(), self.floor, self.x, self.y)
	if not angle then return self:Hide() end
	angle = angle + rad_135

	if GetCVar("rotateMinimap") == "1" then
		--local cring = MiniMapCompassRing:GetFacing()
        local cring = GetPlayerFacing()
		angle = angle - cring
	end
	

	local sin,cos = math.sin(angle) * square_half, math.cos(angle) * square_half
	self.arrow:SetTexCoord(0.5-sin, 0.5+cos, 0.5+cos, 0.5+sin, 0.5-cos, 0.5-sin, 0.5+sin, 0.5-cos)
end






minimap_count = 0;
function Minimap_OnUpdate(self, elapsed)


        local data = self.point
        local srcX,srcY = GHU_Map:GetPlayerLoc()--placeholder function
		---Possbly loop below?
		local dist,x,y = mapfiles:Distance(GetMapInfo(), data.floor, srcX,srcY, data.x, data.y)--src is source and dest is destination, call from table?
		local disabled = self.disabled

		if not dist or IsInInstance() then
			self:Hide()
			return
		end

		minimap_count = minimap_count + elapsed

		if minimap_count < 0.1 then return end

		-- Reset the counter
		minimap_count = 0

		---local edge = Astrolabe:IsIconOnEdge(self)<<--we might be able to do this by taking where the icon is from our current postion,
		
		--local callbacks = data.callbacks

		if edge then
			-- Check to see if this is a transition
			if not disabled then
				self.icon:Hide()
				self.arrow:Show()

				-- Rotate the icon, as required
				local dist,angle = mapfiles:DistanceAndDirection(GetMapInfo(), icon.floor, icon.X, icon.Y)--use the destination x/y
				angle = angle + rad_135

				if GetCVar("rotateMinimap") == "1" then
					--local cring = MiniMapCompassRing:GetFacing()
                    local cring = GetPlayerFacing()
					angle = angle - cring
				end

				local sin,cos = math.sin(angle) * square_half, math.cos(angle) * square_half
				self.arrow:SetTexCoord(0.5-sin, 0.5+cos, 0.5+cos, 0.5+sin, 0.5-cos, 0.5-sin, 0.5+sin, 0.5-cos)
			end
		else
		self.icon:Show()
				self.arrow:Hide()
			
		end
		
		end
		

function World_OnEvent(self, event, ...)
		if event == "WORLD_MAP_UPDATE" then
		  GHU_MAPICONS:MakeIcon(self.worldmap)
	end

	end
	
function GHU_MAPICONS:MakeIcon(point,IsMinimap)
local frame;
if IsMinimap then
frame = "MinimapIco"
else
frame = "WMIco"
end
local refID = point.refID
			
				if _G[frame..refID] then
					if GetMapInfo() == point.mapkey then
					_G[frame..refID]:Show();
                  elseif WorldMapFrame:IsVisible() and (GetMapInfo() ~= point.mapkey) then
                         if (_G[frame..refID]:IsVisible()) then
								_G[frame..refID]:Hide()
                          end
                  else
				_G[frame..refID]:Hide();
				_G[frame..refID] = nil;
					end
						end
					
		
end

-- 	standard
function GHU_MAPICONS:Create(varName,name)
		
	_G[varName]=GHU_MAPICONS; 
	
	local obj = {}             -- our new object
	setmetatable(obj, _G[varName])  -- make GHU_NPC handle lookup
	obj.headerName = name;      -- initialize our object
	
	_G[varName]=obj;
	obj:InitHooks(varName);  
	--obj:NewCurrentNPC();
end
	
function GHU_MAPICONS:Hook(funcName,varName)
	
	if not(type(self.orig)=="table") then self.orig ={}; end
	assert(type(self[funcName])=="function","No function found for "..funcName);
	self.orig[funcName] = _G[funcName];
		
	RunScript("local t = _G[\""..varName.."\"]; t[\"hooked\"][\""..funcName.."\"] = function(...) gself = _G[\""..varName.."\"]; local f = _G[\""..varName.."\"]; return f:"..funcName.."(...); end _G[\""..varName.."\"]=t; ");	

_G[funcName]=_G[varName]["hooked"][funcName];
	end

function GHU_MAPICONS:InitHooks(varName)
	if not(self.isHooked) then
		local obj = _G[varName];
		
		--self:Hook("WORLD_MAP_UPDATE",varName)
		
		--self:Hook("PlaySound",varName)
		
		self.isHooked = true;
	end
end


--GHI:MAPICONS:

--	Hooks
--icona = path to icon name
--refID unique id 
--isPOI true/false
--if isPOI true use a poiicon texture from table
function GHU_MAPICONS:PlaceIcon(icona,refID,isPOI,poiTex)


	local point = table.remove(pool)

	if not point then
		point = {}

		local minimap = CreateFrame("Button", "MinimapIco"..refID, minimapP)
		minimap:SetHeight(20)
		minimap:SetWidth(20)
		minimap:RegisterForClicks("RightButtonUp")

        -- Add to the "All points" table so we can reparent easily
        table.insert(all_points, minimap)

		minimap.icon = minimap:CreateTexture("BACKGROUND")
		if isPOI == true then
		minimap.icon:SetTexture(icona)
		minimap.icon:SetTexCoord(WorldMap_GetPOITextureCoords(poiTex))
		else
		minimap.icon:SetTexture(icona)
		end
		minimap.icon:SetPoint("CENTER", 0, 0)
		minimap.icon:SetHeight(16)
		minimap.icon:SetWidth(16)

		minimap.arrow = minimap:CreateTexture("BACKGROUND")
		minimap.arrow:SetTexture("Interface\\AddOns\\GHU\\textures\\MiniMapArrow0")--
		minimap.arrow:SetPoint("CENTER", 0 ,0)
		minimap.arrow:SetHeight(20)
		minimap.arrow:SetWidth(20)
		minimap.arrow:Hide()

		-- Add the behavior scripts 
		minimap:SetScript("OnEnter", Minimap_OnEnter)
		minimap:SetScript("OnLeave", Minimap_OnLeave)
		minimap:SetScript("OnUpdate", Minimap_OnUpdate)
		minimap:SetScript("OnClick", Minimap_OnClick)
		minimap:RegisterEvent("PLAYER_ENTERING_WORLD")
		minimap:SetScript("OnEvent", Minimap_OnEvent)
		if not GHSTOverlay then
            local overlay = CreateFrame("Frame", "GHSTOverlay", WorldMapButton)
            overlay:SetAllPoints(true)
        end
		
		local worldmap = CreateFrame("Button", "WMIco"..refID, GHSTOverlay)
		worldmap:SetHeight(12)
		worldmap:SetWidth(12)
		worldmap:RegisterForClicks("RightButtonUp")
		worldmap.icon = worldmap:CreateTexture("ARTWORK")
		worldmap.icon:SetAllPoints()
		if isPOI == true then
		worldmap.icon:SetTexture(icona)
		worldmap.icon:SetTexCoord(WorldMap_GetPOITextureCoords(poiTex))
		else
		worldmap.icon:SetTexture(icona)
		end

		worldmap:RegisterEvent("WORLD_MAP_UPDATE")
		worldmap:SetScript("OnEnter", World_OnEnter)
		worldmap:SetScript("OnLeave", World_OnLeave)
		worldmap:SetScript("OnClick", World_OnClick)
		worldmap:SetScript("OnEvent", World_OnEvent)

		point.worldmap = worldmap
		point.minimap = minimap
end
local Continent = GetCurrentMapContinent()
local Zone = GetCurrentMapZone()

C, Z, xPos, yPos = Astrolabe:GetCurrentPlayerPosition()---replce with GHU_MAP call?
point.c = Continent-
point.z = Zone
point.x = xPos
point.y = yPos
point.mapkey = mapfiles:MapAreaId(GetMapInfo()) -- crystalsong forest
point.minimap.point = point
point.worldmap.point = point
point.refID = refID


--print(Astrolabe:GetCurrentPlayerPosition())

---source is http://pilus.info/cms/phpbb/viewtopic.php?f=17&t=965

--Make a function to add tooltips.

--Astrolabe:PlaceIconOnMinimap( point.minimap, Continent, Zone, xPos, yPos )

--Astrolabe:PlaceIconOnWorldMap(WorldMapButton, point.worldmap,Continent, Zone, xPos, yPos )
GHU_MakeIcon(point.minimap,true)

point.minimap:EnableMouse(true)
		point.minimap.disabled = false
		GHrotateArrow(point.minimap)
				GHU_MakeIcon(point.worldmap)

end

function GHU_MAPICONS:RemoveIcon(refID)
local point = refID
	if point then
		--Astrolabe:RemoveIconFromMinimap(point.minimap)--unsure how to do this
		point.minimap:Hide()
		point.worldmap:Hide()

	
		point.refID = nil
		table.insert(pool, point)
	end
end


---may not need belofw..unsure.
function GHU_MAPICONS:MapEvent(refID,event,color)
local point = refID
	if point then
		if event == "attack" then
			iconColor = color or GHU_MAPICONS.iconlist.color["red"];
			point.minimap.Icon:SetVertexColor(iconColor.r,iconColor.g,iconColor.b)


		end
	end

end

function GHU_MAPICONS:MakeSubZone(continent,zone,subzoneName,zoneID)
--put in tables

end

function GHU_MAPICONS:SetZoneType(zoneID,zType,combatZone)
--ztype is sanctuary,arena,friendly,hostile,contested,combat
end

function GHU_MAPICONS:SetZoneOwner(zoneID,faction,status)
end

---Following is blizzard Modified.
ZoneFadeInDuration = 0.5;
ZoneHoldDuration = 1.0;
ZoneFadeOutDuration = 2.0;
ZonePVPType = nil;
 
function GHU_MAPICONS:SetZoneText(showZone)
    local pvpType, isSubZonePvP, factionName = zType,combatZone,faction;--all from tables from above.
    PVPInfoTextString:SetText("");
    local pvpTextString = PVPInfoTextString;
    if ( isSubZonePvP ) then
        pvpTextString = PVPArenaTextString;
    end
 
    if ( pvpType == "sanctuary" ) then
        pvpTextString:SetText(SANCTUARY_TERRITORY);
        pvpTextString:SetTextColor(0.41, 0.8, 0.94);
        ZoneTextString:SetTextColor(0.41, 0.8, 0.94);
        SubZoneTextString:SetTextColor(0.41, 0.8, 0.94);
    elseif ( pvpType == "arena" ) then
        pvpTextString:SetText(FREE_FOR_ALL_TERRITORY);
        pvpTextString:SetTextColor(1.0, 0.1, 0.1);
        ZoneTextString:SetTextColor(1.0, 0.1, 0.1);
        SubZoneTextString:SetTextColor(1.0, 0.1, 0.1);
    elseif ( pvpType == "friendly" ) then
        pvpTextString:SetFormattedText(FACTION_CONTROLLED_TERRITORY, factionName);
        pvpTextString:SetTextColor(0.1, 1.0, 0.1);
        ZoneTextString:SetTextColor(0.1, 1.0, 0.1);
        SubZoneTextString:SetTextColor(0.1, 1.0, 0.1);
    elseif ( pvpType == "hostile" ) then
        pvpTextString:SetFormattedText(FACTION_CONTROLLED_TERRITORY, factionName);
        pvpTextString:SetTextColor(1.0, 0.1, 0.1);
        ZoneTextString:SetTextColor(1.0, 0.1, 0.1);
        SubZoneTextString:SetTextColor(1.0, 0.1, 0.1);
    elseif ( pvpType == "contested" ) then
        pvpTextString:SetText(CONTESTED_TERRITORY);
        pvpTextString:SetTextColor(1.0, 0.7, 0);
        ZoneTextString:SetTextColor(1.0, 0.7, 0);
        SubZoneTextString:SetTextColor(1.0, 0.7, 0);
    elseif ( pvpType == "combat" ) then
        pvpTextString:SetText(COMBAT_ZONE);
        pvpTextString:SetTextColor(1.0, 0.1, 0.1);
        ZoneTextString:SetTextColor(1.0, 0.1, 0.1);
        SubZoneTextString:SetTextColor(1.0, 0.1, 0.1);
    else
        ZoneTextString:SetTextColor(1.0, 0.9294, 0.7607);
        SubZoneTextString:SetTextColor(1.0, 0.9294, 0.7607);
    end
 
    if ( ZonePVPType ~= pvpType ) then
        ZonePVPType = pvpType;
--              FadingFrame_Show(ZoneTextFrame);
    elseif ( not showZone ) then
        PVPInfoTextString:SetText("");
        SubZoneTextString:SetPoint("TOP", "ZoneTextString", "BOTTOM", 0, 0);
    end
 
    if ( PVPInfoTextString:GetText() == "" ) then
        SubZoneTextString:SetPoint("TOP", "ZoneTextString", "BOTTOM", 0, 0);
    else
        SubZoneTextString:SetPoint("TOP", "PVPInfoTextString", "BOTTOM", 0, 0);
    end
end
 
function GHU_MAPICONS:ZoneText_OnLoad(self)
    FadingFrame_OnLoad(self);
    FadingFrame_SetFadeInTime(self, ZoneFadeInDuration);
    FadingFrame_SetHoldTime(self, ZoneHoldDuration);
    FadingFrame_SetFadeOutTime(self, ZoneFadeOutDuration);
    self:RegisterEvent("ZONE_CHANGED");
    self:RegisterEvent("ZONE_CHANGED_INDOORS");
    self:RegisterEvent("ZONE_CHANGED_NEW_AREA");
    self.zoneText = "";
    ZonePVPType = nil;
end
 
function GHU_MAPICONS:ZoneText_OnEvent(self, event, ...)
    local showZoneText = false;
    local zoneText = GetZoneText();
    if ( (zoneText ~= self.zoneText) or (event == "ZONE_CHANGED_NEW_AREA") ) then
        self.zoneText = zoneText;
        ZoneTextString:SetText( zoneText );
        showZoneText = true;
        SetZoneText( showZoneText );
        FadingFrame_Show( self );
    end
     
    local subzoneText = GetSubZoneText();
    if ( subzoneText == "" and not showZoneText) then
        subzoneText = zoneText;
    end
    SubZoneTextString:SetText( "" );
 
    if ( subzoneText == zoneText ) then
        showZoneText = false;
        if ( not self:IsShown() ) then
            SubZoneTextString:SetText( subzoneText );
            SetZoneText( showZoneText );
            FadingFrame_Show( SubZoneTextFrame );
        end
    else
        if (self:IsShown()) then
            showZoneText = true;
        end
        SubZoneTextString:SetText( subzoneText );
        SetZoneText( showZoneText );
        FadingFrame_Show( SubZoneTextFrame );
    end
end
 
function GHU_MAPICONS:SubZoneText_OnLoad(self)
    FadingFrame_OnLoad(self);
    FadingFrame_SetFadeInTime(self, ZoneFadeInDuration);
    FadingFrame_SetHoldTime(self, ZoneHoldDuration);
    FadingFrame_SetFadeOutTime(self, ZoneFadeOutDuration);
    PVPArenaTextString:SetTextColor(1.0, 0.1, 0.1);
    SetZoneText(true);
    SubZoneTextString:SetText(GetSubZoneText());
end
function GHUSTT()
---yes i know i am doing it wrong here
local poi = GHU_MAPICONS.iconlist.poi;
--print(poi.town)
GHU_MAPICONS:PlaceIcon(ghstPOI,"test",true,poi.town)
GHU_MAPICONS:MapEvent(refID,event,color)
end
