--***********************************************************************
--Title: wowshell core
--Description: A set of register and WSVar-access functions
--Author: Robin 月色狼影
--Revision: $Rev: 3816 $
--LastUpadate: $Id: WoWShell.lua 3816 2010-09-23 04:33:04Z yaroot $
--:
--***********************************************************************
local name, addon = ...;
local Version = GetAddOnMetadata("WoWShell", "Version");
local L = wsLocale:GetLocale("WoWShell");

WS_VERSION = "|cFF34A2F7"..L["版本"]..": "..Version.."|r";

WS_CONFIG_MAX_SECTIONS = 3;
WS_CONFIG_MAX_CLASSES = 7;
WS_CONFIG_MAX_SLOTNUM = 19;
showedUpdateReminder = false;--设置提醒更新功能
WS_IGNOREERROR = L["屏蔽"];

--WS_CONFIG = {
--	LANG_CHINESE = 1;
--	enablegs = true;
--};

function WS_OnLoad(self)
	self:RegisterEvent("VARIABLES_LOADED");
	self:RegisterEvent("PLAYER_LOGIN")
	self:RegisterEvent("ADDON_LOADED");
	self:RegisterEvent("UI_ERROR_MESSAGE");
	self:RegisterEvent("CHAT_MSG_ADDON");
	self:RegisterEvent("RAID_ROSTER_UPDATE");
	self:RegisterEvent("PARTY_MEMBERS_CHANGED");
	--UIErrorsFrame:SetScript("OnEvent", nil)--nil

	UIErrorsFrame:SetFrameStrata('LOW')

	SlashCmdList["WSV"] = function()
		WS_GUI:ToggleFrame(true)
	end;
	SLASH_WSV1 = "/wowshell";
	SLASH_WSV2 = "/ws";

	SLASH_RL1 = "/rl";
	SlashCmdList["RL"] = function(msg)
		ReloadUI()
	end

	SLASH_WSTELE1 = '/wstele'
	SLASH_WSTELE2 = '/tele'

	function SlashCmdList.WSTELE()
		local inInstance, instanceType = IsInInstance()
		LFGTeleport(instanceType and instanceType == 'party')
	end


	--hooksecurefunc("PickupContainerItem",WS_PickupContainerItem);
	SetCVar('profanityFilter', '0')
	SetCVar('cameraDistanceMax', '25')
	--SetCVar('taintLog', '2')

	local textures = {
		Otravi  	 = "AceBarFrames.tga",
		Smooth 		 = "smooth.tga",
		Gloss  		 = "Gloss.tga",
		BantoBar	 = "BantoBar.tga",
		Aluminium	 = "Aluminium.tga",
		Perl		 = "perl.tga",
		Glaze		 = "glaze.tga",
		Charcoal	 = "Charcoal.tga",
		Otravi		 = "otravi.tga",
		Striped		 = "striped.tga",
		LiteStep	 = "LiteStep.tga",
		Minimalist	 = "Minimalist.tga",
		Frost		= "Frost.tga",
		Healbot		= "Healbot.tga",
		Rocks		= "Rocks.tga",
		Runes		= "Runes.tga",
		Xeon		= "Xeon.tga"
	}

	local SM = LibStub("LibSharedMedia-3.0");
	if(SM) then
		local path = [[Interface\AddOns\Wowshell\texture\statusbar\]]
		for k, v in next, textures do
			SM:Register("StatusBar", k, path .. v)
		end
	end
end

function wsGameMenuButton_OnLoad(self)
	self:SetText(L["AddOns"])
end

function WS_PlaceAction(slot)
	CursorAction = {};
	Original_PlaceAction(slot);
end

------------------------------------------------
-- ** sync mod
------------------------------------------------
local function sendSync(prefix, msg)
	local zoneType = select(2, IsInInstance())
	if zoneType == "pvp" or zoneType == "arena" then
		SendAddonMessage(prefix, msg, "BATTLEGROUND")
	elseif GetNumGroupMembers() > 0 then
		SendAddonMessage(prefix, msg, "RAID");
	elseif GetNumSubgroupMembers() > 0 then
		SendAddonMessage(prefix, msg, "PARTY");
	elseif IsInGuild() then
		SendAddonMessage(prefix, msg, "GUILD");
	else
		SendAddonMessage(prefix, msg);
	end
end

local function ShowUpdateReminder(newVersion)
	local frame = CreateFrame("Frame", nil, UIParent)
	frame:SetFrameStrata("DIALOG")
	frame:SetWidth(430)
	frame:SetHeight(155)
	frame:SetPoint("TOP", 0, -230)
	frame:SetBackdrop({
		bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
		edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border", tile = true, tileSize = 32, edgeSize = 32,
		insets = {left = 11, right = 12, top = 12, bottom = 11},
	})
	local fontstring = frame:CreateFontString(nil, "ARTWORK", "GameFontNormal")
	fontstring:SetWidth(410)
	fontstring:SetHeight(0)
	fontstring:SetPoint("TOP", 0, -16)
	fontstring:SetText((L["你的魔兽精灵版本已过期。请使用更新器更新到最新版本。\n你可以在如下地址下载到新版本%s："]):format(newVersion))
	local editBox = CreateFrame("EditBox", nil, frame)
	do
		local editBoxLeft = editBox:CreateTexture(nil, "BACKGROUND")
		local editBoxRight = editBox:CreateTexture(nil, "BACKGROUND")
		local editBoxMiddle = editBox:CreateTexture(nil, "BACKGROUND")
		editBoxLeft:SetTexture("Interface\\ChatFrame\\UI-ChatInputBorder-Left")
		editBoxLeft:SetHeight(32)
		editBoxLeft:SetWidth(32)
		editBoxLeft:SetPoint("LEFT", -14, 0)
		editBoxLeft:SetTexCoord(0, 0.125, 0, 1)
		editBoxRight:SetTexture("Interface\\ChatFrame\\UI-ChatInputBorder-Right")
		editBoxRight:SetHeight(32)
		editBoxRight:SetWidth(32)
		editBoxRight:SetPoint("RIGHT", 6, 0)
		editBoxRight:SetTexCoord(0.875, 1, 0, 1)
		editBoxMiddle:SetTexture("Interface\\ChatFrame\\UI-ChatInputBorder-Right")
		editBoxMiddle:SetHeight(32)
		editBoxMiddle:SetWidth(1)
		editBoxMiddle:SetPoint("LEFT", editBoxLeft, "RIGHT")
		editBoxMiddle:SetPoint("RIGHT", editBoxRight, "LEFT")
		editBoxMiddle:SetTexCoord(0, 0.9375, 0, 1)
	end
	editBox:SetHeight(32)
	editBox:SetWidth(250)
	editBox:SetPoint("TOP", fontstring, "BOTTOM", 0, -4)
	editBox:SetFontObject("GameFontHighlight")
	editBox:SetTextInsets(0, 0, 0, 1)
	editBox:SetFocus()
	editBox:SetText("http://www.wowshell.com")
	editBox:HighlightText()
	editBox:SetScript("OnHide", function(self)
		if ChatFrameEditBox:IsVisible() then
			ChatFrameEditBox:SetFocus()
		end
	end)
	editBox:SetScript("OnTextChanged", function(self)
		editBox:SetText("http://www.wowshell.com")
		editBox:HighlightText()
	end)
	local fontstring = frame:CreateFontString(nil, "ARTWORK", "GameFontNormal")
	fontstring:SetWidth(410)
	fontstring:SetHeight(0)
	fontstring:SetPoint("TOP", editBox, "BOTTOM", 0, 0)
	fontstring:SetText(L["Ctrl-C：复制下载地址到剪切板。"])
	local button = CreateFrame("Button", nil, frame)
	button:SetHeight(24)
	button:SetWidth(75)
	button:SetPoint("BOTTOM", 0, 13)
	button:SetNormalFontObject("GameFontNormal")
	button:SetHighlightFontObject("GameFontHighlight")
	button:SetNormalTexture(button:CreateTexture(nil, nil, "UIPanelButtonUpTexture"))
	button:SetPushedTexture(button:CreateTexture(nil, nil, "UIPanelButtonDownTexture"))
	button:SetHighlightTexture(button:CreateTexture(nil, nil, "UIPanelButtonHighlightTexture"))
	button:SetText(CLOSE)
	button:SetScript("OnClick", function(self)
		frame:Hide()
	end)
end

do
	DEFAULT_CHAT_FRAME:HookScript("OnHyperlinkClick", function(self, link, string, button, ...)
		local linkType, arg1, arg2, arg3 = strsplit(":", link)
		if linkType == "WS" and arg1 == "update" then
			ShowUpdateReminder(arg2) -- displayVersion, revision
		end
	end)

	local old = ItemRefTooltip.SetHyperlink -- we have to hook this function since the default ChatFrame code assumes that all links except for player and channel links are valid arguments for this function
	function ItemRefTooltip:SetHyperlink(link, ...)
		if link:match("^WS") then return end
		return old(self, link, ...)
	end
end

local syncHandlers = {
	["Wowshell-Ver"] = function(msg, channel, sender)
		if msg == "VersionCheck" then
			sendSync("Wowshell-Ver", ("%s\t%s"):format(Version, GetLocale()));
		else
			local version, locale = strsplit("\t", msg);
			local a, b, c, realversion = strsplit(".", version);--new
			realversion = tonumber(realversion);
			if realversion then
				--get local version
				local _, _, _, realseversion = strsplit(".", Version);--old
				if realversion > tonumber(realseversion) and not showedUpdateReminder then
					local v = a.."."..b.."."..c.."."..realversion;
					showedUpdateReminder = true;

					DEFAULT_CHAT_FRAME:AddMessage((L["你的魔兽精灵版本已过期。请使用更新器更新到最新版本。\n你可以在如下地址下载到新版本%s："]):match("([^\n]*)"));
					DEFAULT_CHAT_FRAME:AddMessage((L["你的魔兽精灵版本已过期。请使用更新器更新到最新版本。\n你可以在如下地址下载到新版本%s："]):match("\n(.*)"):format(v));
					DEFAULT_CHAT_FRAME:AddMessage(("|HWS:update:%s|h|cff3588ff[http://www.wowshell.com]"):format(v));
				end
			end
		end
	end
}
------------------------------------------------------------------------------------------------

function WS_TOGGLE_BLIZ_AB_ART()
	local func = WS_CONFIG.hide_bliz_ab_art and MainMenuBarLeftEndCap.Hide or MainMenuBarLeftEndCap.Show
	func(MainMenuBarRightEndCap)
	func(MainMenuBarLeftEndCap)
end

--need fix
function WS_OnEvent(self, event, ...)
	if (event == "VARIABLES_LOADED" or event == "PLAYER_LOGIN") then

		sendSync("Wowshell-Ver", "VersionCheck");
		local _, class = UnitClass("player");
		if class == "HUNTER" then
			LoadAddOn("Wowshell_HunterHelper");
		end
		WS_CONFIG = WS_CONFIG or {}

		--if (class and class == "SHAMAN") then
		--	LoadAddOn("TotemTimers");
		--end

		--if(class and class == "WARLOCK") then
		--	--LoadAddOn("Warlock")
		--end
		--if (class and class == "DRUID") then
		--	LoadAddOn("Wowshell_DruidHelper")
		--end

		--if WS_CONFIG["enablegs"] == nil then
		--	WS_CONFIG["enablegs"] = true;
		--end
		WS_TOGGLE_BLIZ_AB_ART()

		--move
	elseif (event == "UI_ERROR_MESSAGE") then
		local msg = ...
	elseif (event == "CHAT_MSG_ADDON") then
		local prefix, msg, channel, sender = ...
		if msg and channel ~= "WHISPER" then
			local handler = syncHandlers[prefix];
			if handler then
				handler(msg, channel, sender);
			end
		end
	elseif (event == "PARTY_MEMBERS_CHANGED" or event == "RAID_ROSTER_UPDATE") then
		sendSync("Wowshell-Ver", "VersionCheck");
	end
end

function WS_OnUpdate(self, elapsed)

end

function wsShowTooltip(tip)
	GameTooltip:SetOwner(this, "ANCHOR_RIGHT")

	if (tip) then
		GameTooltip:AddLine(tip, 1, 1, 1, 1)
	end

	GameTooltip:Show();
end

StaticPopupDialogs['WOWSHELL_UTIL_RELOAD'] = {
	text = L[GetLocale() == 'zhTW' and '重載界面-是否重載界面？' or '重载界面 - 是否重载界面?'],
	button1 = YES,
	button2 = NO,
	OnAccept = function()
		ReloadUI()
	end,
	--OnCancel = function()
		--    lolly.db.simple = not lolly.db.simple
		--end,
		hideOnEscape = 1,
		timeout = 0,
		exclusive = 1,
		whileDead = 1,
	}

	StaticPopupDialogs['WOWSHELL_UTIL_CONFIGCHANGED_RELOAD'] = {
		text = L[GetLocale() == 'zhTW' and '你修改的設置要求重載界面生效，你可以在調整其他設置後再輸入 /rl 重載' or '你修改的设置要求重载界面生效, 你可以在调整其他设置后输入 /rl 重载'],
	}

	--[[StaticPopupDialogs['WOWSHELL_PARTY_OFFSET_CHANGED_RELOAD'] = {
		text = L[GetLocale() == 'zhTW' and '修改此项将改变小队间距,修改后的设置将在重载界面后生效'],
		button1 = 'YES',
		button2 = 'NO',
		OnAccept = function()
			ReloadUI()
		end,
		hideOnEscape = true,
		timeout = 0,
		exclusive = true,
		whileDead = true,
	}]]


	for k, v in next, StaticPopupDialogs['WOWSHELL_UTIL_RELOAD'] do
		if(not StaticPopupDialogs['WOWSHELL_UTIL_CONFIGCHANGED_RELOAD'][k]) then
			StaticPopupDialogs['WOWSHELL_UTIL_CONFIGCHANGED_RELOAD'][k] = v
		end
		
	end
	--for k, v in next, StaticPopupDialogs['WOWSHELL_UTIL_RELOAD'] do
		--if(not StaticPopupDialogs['WOWSHELL_PARTY_OFFSET_CHANGED_RELOAD'][k]) then
			--StaticPopupDialogs['WOWSHELL_PARTY_OFFSET_CHANGED_RELOAD'][k] =v
		--end
	--end

	wsPopup = {
		CFG_RELOAD = function()
			StaticPopup_Show'WOWSHELL_UTIL_CONFIGCHANGED_RELOAD'
			--StaticPopup_Show'WOWSHELL_PARTY_OFFSET_CHANGED_RELOAD'
		end,
	}

	do
		--[[
		--      xpcall safecall
		--      copy from ace3
		--]]
		local geterrorhandler = geterrorhandler
		local setmetatable = setmetatable
		local next, xpcall = next, xpcall
		local rawset, assert, loadstring = rawset, assert, loadstring
		local tconcat = table.concat

		local function errorhandler(err)
			return geterrorhandler()(err)
		end

		local CreateDispatcher = function(argCount)
			local code = [[
			local xpcall, eh = ...
			local method, ARGS
			local function call() return method(ARGS) end

			local function dispatch(func, ...)
				method = func
				if not method then return end
				ARGS = ...
				return xpcall(call, eh)
			end

			return dispatch
			]]

			local ARGS = {}
			for i = 1, argCount do ARGS[i] = "arg"..i end
			code = code:gsub("ARGS", tconcat(ARGS, ", "))
			return assert(loadstring(code, "safecall Dispatcher["..argCount.."]"))(xpcall, errorhandler)
		end

		local Dispatchers = setmetatable({}, {__index=function(self, argCount)
			local dispatcher = CreateDispatcher(argCount)
			rawset(self, argCount, dispatcher)
			return dispatcher
		end})
		Dispatchers[0] = function(func)
			return xpcall(func, errorhandler)
		end

		wsSafeCall = function( func, ... )
			return Dispatchers[select('#', ...)](func, ...)
		end

	local SetCVar, BNGetMatureLanguageFilter, BNSetMatureLanguageFilter = 
	  SetCVar, BNGetMatureLanguageFilter, BNSetMatureLanguageFilter
		local eventFr=CreateFrame("Frame")
		local function set() SetCVar("profanityFilter","0") if BNGetMatureLanguageFilter() then BNSetMatureLanguageFilter(false) end end
		eventFr:SetScript("OnEvent",set)
		eventFr:RegisterEvent("CVAR_UPDATE")
		eventFr:RegisterEvent("VARIABLES_LOADED")
		eventFr:RegisterEvent("BN_MATURE_LANGUAGE_FILTER")
		do set() end

	end
