WindChatTimeConfig = {};

function WindChat_OnLoad()
	local name = WindChat_getBlzFrame(this:GetName());
	local frame = getglobal(name);
	WindChat_setBackground(this, frame, 6);
	WindCommon_setHide(getglobal(name.."UpButton"));
	WindCommon_setHide(getglobal(name.."DownButton"));

	local bottom = getglobal(name.."BottomButton");
	WindCommon_setSize(bottom, 24, 24);
	WindCommon_setPoint(bottom, "BOTTOMRIGHT", frame, "BOTTOMRIGHT", 0, 0);
	WindCommon_setHide(bottom);
end

function WindChat_OnUpdate()
	local name = WindChat_getBlzFrame(this:GetName());
	local frame = getglobal(name);
	if (frame:AtBottom()) then WindCommon_setHide(getglobal(name.."BottomButton"));
	else
		WindChat_viewBottomButton(getglobal(name.."BottomButton"), frame);
	end
end

function WindChat_setBackground(bg, frame, inset)
	local minset = inset * (-1);
	bg:ClearAllPoints();
	bg:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", minset-4, minset-4);
	bg:SetPoint("TOPLEFT", frame, "TOPLEFT", minset-4, inset-2);
	bg:SetPoint("TOPRIGHT", frame, "TOPRIGHT", inset, inset-2);
	bg:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", inset, minset-4);
	WindCommon_setBackgroundLevel(bg, frame);
end

function WindChat_getBlzFrame(name)
	return string.sub(name, 5);
end

function WindChat_OnMouseWheel(value)
	local name = WindChat_getBlzFrame(this:GetName());
	local frame = getglobal(name);
	if ( value < 0 ) then
		if IsShiftKeyDown() then frame:ScrollToBottom();
		elseif IsControlKeyDown() then
			frame:ScrollDown();
			frame:ScrollDown();
			frame:ScrollDown();
		else frame:ScrollDown(); end
	elseif ( value > 0 ) then
		if IsShiftKeyDown() then frame:ScrollToTop();
		elseif IsControlKeyDown() then
			frame:ScrollUp();
			frame:ScrollUp();
			frame:ScrollUp();
		else frame:ScrollUp(); end
	end
end

function WindChat_viewBottomButton(bottom, frame)
	WindCommon_setPoint(bottom, "BOTTOMRIGHT", frame, "BOTTOMRIGHT", 0, 0);
	WindCommon_setSize(bottom, 24, 24);
	bottom:SetAlpha(1.0);
end

function WindChatEditBox_OnLoad()
	WindChat_setChatFrameMenuButton();

	ChatFrameEditBoxLeft:ClearAllPoints();
	ChatFrameEditBoxLeft:SetPoint("LEFT", "ChatFrame1", "LEFT", 0, 0);
	ChatFrameEditBoxLeft:SetPoint("RIGHT", "ChatFrame1", "RIGHT", 0, 0);	
	ChatFrameEditBoxLeft:Hide();
	ChatFrameEditBoxRight:Hide();

	WindCommon_setBackground(this, ChatFrameEditBox, 1);
	WindCommon_setBackgroundPoint(WindChatEditBoxBG, WindChatEditBox, -4);
	WindCommon_setPoint(ChatFrameEditBoxLanguage, "LEFT", "ChatFrameEditBox", "RIGHT", -6, 0);

	SetItemRef = WindChat_SetItemRef;

	ChatFrameEditBox:SetAltArrowKeyMode(false);
	ChatFrameEditBox:SetBackdrop(WindCommon_ColorBorder);
	ChatFrameEditBox:SetBackdropColor{0.0, 0.0, 0.0, 1.0};
	ChatFrameEditBox:SetHeight(30);
	ChatFrameEditBox:SetFrameStrata("TOOLTIP");
	WindChatEditBox:RegisterEvent("VARIABLES_LOADED");
end

function WindChat_setChatFrameMenuButton()
	WindCommon_setSize(ChatFrameMenuButton, 20, 20);
	WindCommon_setPoint(ChatFrameMenuButton, "TOPRIGHT", "ChatFrame1", "TOPRIGHT", 0, 0);
	ChatFrameMenuButton:SetAlpha(0.4);
end

function WindChat_SetItemRef(link, text, button)
	if ( strsub(link, 1, 6) == "player" ) then
		WindChat_SetItemRefPlayer(link, button);
		return;
	end

	if ( IsControlKeyDown() ) then DressUpItemLink(text);
	elseif ( IsShiftKeyDown() ) then
		if ( ChatFrameEditBox:IsVisible() ) then 
			ChatFrameEditBox:Insert(text);
		elseif (WIM_EditBoxInFocus) then 
			WIM_EditBoxInFocus:Insert(text); 
		end
	else
		ShowUIPanel(ItemRefTooltip);
		if ( not ItemRefTooltip:IsVisible() ) then ItemRefTooltip:SetOwner(UIParent, "ANCHOR_PRESERVE"); end
		ItemRefTooltip:SetHyperlink(link);
	end
end

function WindChat_SetItemRefPlayer(link, button)
	local namelink = strsub(link, 8);
	local name, lineid = strsplit(":", namelink);
	if ( name and (strlen(name) > 0) ) then
		name = gsub(name, "([^%s]*)%s+([^%s]*)%s+([^%s]*)", "%3");
		name = gsub(name, "([^%s]*)%s+([^%s]*)", "%2");
		if ( IsShiftKeyDown() ) then 
			local staticPopup;
			staticPopup = StaticPopup_Visible("ADD_IGNORE");
			if ( staticPopup ) then	
				getglobal(staticPopup.."EditBox"):SetText(name); 
				return; 
			end
			staticPopup = StaticPopup_Visible("ADD_FRIEND");
			if ( staticPopup ) then	
				getglobal(staticPopup.."EditBox"):SetText(name); 
				return; 
			end
			staticPopup = StaticPopup_Visible("ADD_GUILDMEMBER");
			if ( staticPopup ) then 
				getglobal(staticPopup.."EditBox"):SetText(name); 
				return; 
			end
			staticPopup = StaticPopup_Visible("ADD_RAIDMEMBER");
			if ( staticPopup ) then 
				getglobal(staticPopup.."EditBox"):SetText(name); 
				return; 
			end
			if ( ChatFrameEditBox:IsVisible() ) then 
				ChatFrameEditBox:Insert(name);
			else 
				SendWho("n-"..name); 
			end		
		elseif ( button == "RightButton" ) then FriendsFrame_ShowDropdown(name, 1, lineid);
		elseif ( IsAltKeyDown() ) then InviteUnit(name);
		elseif ( IsControlKeyDown() ) then AddFriend(name);
		elseif (StaticPopup_Visible("ADD_IGNORE")) then getglobal(staticPopup.."EditBox"):SetText(name);
		else ChatFrame_SendTell(name); end
	end
end

function WindChatEditBox_OnEvent()
	if (event == "VARIABLES_LOADED") then
		if ( WindChat_Date ~= date("%m") and WindChat_Names) then
			DEFAULT_CHAT_FRAME:AddMessage("이월됨에 따라서 ".."|cffffff00".."WTF\\Account\\계정명\\SavedVariables\\WindChat.lua".."|r".."\n파일의 ".."|cff20ff20".." [\"이름\"] = \"색상값\"".."|cffff0000".." 정보를 초기화 ".."|r".."합니다.")
			WindChat_Names = {};
			WindChat_Date = date("%m");
		end
		WindChat_initConfig();
		WindChatEditBox_setLocation();
		for i=1,7 do
			WindChat_setScale(i);
			WindChat_setBorder(i);
		end
		WindChat_setColor();
		WindChat_setTime();
		WindChat_setSticky();
		WindChat_setStrings();
	end
end

function WindChat_initConfig()
	if (not WindChatConfigAll) then WindChatConfigAll = WindChatDefault; end
	for i=1, 7 do
		if (WindChatConfigAll[i][3] == nil) then WindChatConfigAll[i][3] = false; end
	end
	for i=1, 7 do
		getglobal("WindChatFrame"..i.."_initColor")();
	end

	WindChat_initTimeColor(); 
end

function WindChat_initTimeColor()
	if (IsAddOnLoaded("WindConfig")) then WindChatConfig_OnShow(); end
end

function WindChatFrame1_initColor()
	if (IsAddOnLoaded("WindConfig")) then WindChatConfig_OnShow();
	WindChatConfig_changeColor(color); end
end

function WindChatFrame2_initColor()
	if (IsAddOnLoaded("WindConfig")) then WindChatConfig_OnShow();
	WindChatConfig_changeColor(color); end
end

function WindChatFrame3_initColor()
	if (IsAddOnLoaded("WindConfig")) then WindChatConfig_OnShow();
	WindChatConfig_changeColor(color); end
end

function WindChatFrame4_initColor()
	if (IsAddOnLoaded("WindConfig")) then WindChatConfig_OnShow();
	WindChatConfig_changeColor(color); end
end

function WindChatFrame5_initColor()
	if (IsAddOnLoaded("WindConfig")) then WindChatConfig_OnShow();
	WindChatConfig_changeColor(color); end
end

function WindChatFrame6_initColor()
	if (IsAddOnLoaded("WindConfig")) then WindChatConfig_OnShow();
	WindChatConfig_changeColor(color); end
end

function WindChatFrame7_initColor()
	if (IsAddOnLoaded("WindConfig")) then WindChatConfig_OnShow();
	WindChatConfig_changeColor(color); end
end

function WindChat_setScale(index)
	getglobal("ChatFrame"..index):SetScale(WindChatConfigAll[index][1]);
	if (index == 1) then ChatFrameEditBox:SetScale(WindChatConfigAll[1][1]); end
end

function WindChat_setBorder(index)
	if (WindChatConfigAll[index][2]) then getglobal("WindChatFrame"..index):SetBackdrop(WindCommon_ColorBorder);
	WindChat_setColor();
	else getglobal("WindChatFrame"..index):SetBackdrop(nil); end
end

function WindChat_setColor()
	for i=1,7 do
		getglobal("WindChatFrame"..i):SetBackdropBorderColor(WindChatConfigAll[i][4][1].r, WindChatConfigAll[i][4][1].g, WindChatConfigAll[i][4][1].b, WindChatConfigAll[i][4][1].a);
		getglobal("WindChatFrame"..i):SetBackdropColor(WindChatConfigAll[i][4][2].r, WindChatConfigAll[i][4][2].g, WindChatConfigAll[i][4][2].b, WindChatConfigAll[i][4][2].a);
	end
	ChatFrameEditBox:SetBackdropBorderColor(WindChatConfigAll[1][4][1].r, WindChatConfigAll[1][4][1].g, WindChatConfigAll[1][4][1].b, WindChatConfigAll[1][4][1].a);
end

function WindChat_resetColor(frameIndex)
	WindChatConfigAll[frameIndex][4] = WindChatDefault[frameIndex][4];
	WindChat_setColor();
end

function WindChatEditBox_setLocation()
	if (WindChatConfigAll[8]) then
		ChatFrameEditBox:ClearAllPoints();
		ChatFrameEditBox:SetPoint("BOTTOMLEFT", "ChatFrame1", "TOPLEFT", -10, 0);
		ChatFrameEditBox:SetPoint("BOTTOMRIGHT", "ChatFrame1", "TOPRIGHT", 6, 0);
	else
		ChatFrameEditBox:ClearAllPoints();
		ChatFrameEditBox:SetPoint("TOPLEFT", "ChatFrame1", "BOTTOMLEFT", -10, -7);
		ChatFrameEditBox:SetPoint("TOPRIGHT", "ChatFrame1", "BOTTOMRIGHT", 6, -7);
	end
end

function WindChat_setSticky()
	if (WindChatConfigAll[13]) then
		ChatTypeInfo["CHANNEL"].sticky = 1;
		ChatTypeInfo["OFFICER"].sticky = 1;
		ChatTypeInfo["RAID_WARNING"].sticky = 1;
		ChatTypeInfo["BATTLEGROUND_LEADER"].sticky = 1;
	else
		ChatTypeInfo["CHANNEL"].sticky = 0;
		ChatTypeInfo["OFFICER"].sticky = 0;
		ChatTypeInfo["RAID_WARNING"].sticky = 0;
		ChatTypeInfo["BATTLEGROUND_LEADER"].sticky = 0;
	end
end

function WindChat_setStrings()
	if (WindChatConfigAll[14]) then
		CHAT_FLAG_GM = "<GM>";
		CHAT_FLAG_AFK = "<비움> ";
		CHAT_FLAG_DND = "<용무중> ";
		CHAT_WHISPER_GET = "%s▶:\32";
		CHAT_WHISPER_INFORM_GET = "%s◀:\32";
		CHAT_MONSTER_YELL_GET = "[Y] %s:\32";
		CHAT_GUILD_GET = "[G] %s:\32";
		CHAT_RAID_GET = "[R] %s:\32";
		CHAT_RAID_LEADER_GET = "[RL] %s:\32";
		CHAT_RAID_WARNING_GET = "[RW] %s:\32";
		CHAT_BATTLEGROUND_GET = "[BP] %s:\32";
		CHAT_BATTLEGROUND_LEADER_GET = "[BFL] %s:\32";
		CHAT_PARTY_GET = "[P] %s:\32";
		CHAT_OFFICER_GET = "[GM] %s:\32";
		CHAT_YELL_GET = "[Y] %s:\32";
	else
		CHAT_FLAG_GM = "<GM>";
		CHAT_FLAG_AFK = "<자리비움> ";
		CHAT_FLAG_DND = "<다른용무중> ";
		CHAT_WHISPER_GET = "%s님의 귓속말:\32";
		CHAT_WHISPER_INFORM_GET = "%s님에게 귓속말:\32";
		CHAT_MONSTER_YELL_GET = "%s의 외침:\32";
		CHAT_GUILD_GET = "[길드] %s:\32";
		CHAT_RAID_GET = "[레이드] %s:\32";
		CHAT_RAID_LEADER_GET = "[공격대장] %s:\32";
		CHAT_RAID_WARNING_GET = "[공격대경보] %s:\32";
		CHAT_BATTLEGROUND_GET = "[전장] %s:\32";
		CHAT_BATTLEGROUND_LEADER_GET = "[전장 지휘관] %s:\32";
		CHAT_PARTY_GET = "[파티] %s:\32";
		CHAT_OFFICER_GET = "[GM] %s:\32";
		CHAT_YELL_GET = "%s님의 외침:\32";
	end
end

local Original_ChatFrame_OnEvent

function WindChatTime_OnLoad()
	Original_ChatFrame_OnEvent = ChatFrame_OnEvent;
	ChatFrame_OnEvent = WindChat_ChatFrame_OnEvent;
	WindChat_Names = {};
end

function WindChat_ChatFrame_OnEvent(event)
	if ( strsub(event, 1, 8) == "CHAT_MSG" and arg2) then
		if ( WindChatConfigAll[16] ) then
			WindChat_setNameColor(event, arg2);
		end
	end
	if (not this.Original_AddMessage) then
		this.Original_AddMessage = this.AddMessage;
		this.AddMessage = WindChat_AddMessage;
	end
	Original_ChatFrame_OnEvent(event);
end

function WindChat_setTime()
	for i=1, 7 do
		if (WindChatConfigAll[i][3]) then
			WindChatTimeConfig["WindChatFrame"..i] = true;
		else
			WindChatTimeConfig["WindChatFrame"..i] = false;
		end
	end
end

function WindChat_setNameColor(event, arg2)
	if ( event ) then
		if ( event == "CHAT_MSG_PARTY" ) then
			local numParty = GetNumPartyMembers();
			for i=1, numParty do
				if ( UnitName("party"..i) == arg2 ) then
					localizedClass, englishClass = UnitClass("party"..i);
					WindChat_ClassData(arg2, localizedClass);
				elseif ( UnitName("player") == arg2 ) then
					localizedClass, englishClass = UnitClass("player");
					WindChat_ClassData(arg2, localizedClass);
				end
			end
		end
		if (event == "CHAT_MSG_RAID" or event == "CHAT_MSG_RAID_LEADER" ) then
			for i=1, MAX_RAID_MEMBERS do
				local name, _, _, _, class = GetRaidRosterInfo(i);
				if ( name and name == arg2 ) then
					WindChat_ClassData(arg2, class);
				end
			end
		end
	else
		return WindChat_ClassData(arg2);
	end
end

function WindChat_ClassData(arg2, class )
	if arg2 then
		arg2 = string.upper(arg2);
	else
		return "";
	end
	if not WindChat_Names then
		WindChat_Names = {};
	end
	if class then
		class = string.upper(class);
		local found;
		for name, color in pairs(WindChat_Names) do
			if name == arg2 then
				found = true;
			end
		end
		if (not found)then
			local color = WindChat_GetClassColor( class );
			WindChat_Names[arg2] = color;
		end
	else
		if (WindChatConfigAll[16]) then
			for name, color in pairs(WindChat_Names) do
				if name == arg2 then
					return color;
				end
			end
		end

	end
	return "";
end

function WindChat_GetClassColor( class )
	local classcolor = "";
	if (class == "마법사") then
		classcolor = "|cff68ccef";
	elseif (class == "흑마법사") then
		classcolor = "|cff9382C9";
	elseif (class == "사제") then
		classcolor = "|cffffffff";
	elseif (class == "드루이드") then
		classcolor = "|cffff7c0a";
	elseif (class == "주술사") then
		classcolor = "|cff245aff";
	elseif (class == "성기사") then
		classcolor = "|cfff48cba";
	elseif (class == "도적") then
		classcolor = "|cfffff468";
	elseif (class == "사냥꾼") then
		classcolor = "|cffaad372";
	elseif (class == "전사") then
		classcolor = "|cffc69b6d";
	end
	return classcolor;
end

function WindChat_AddMessage(this, msg, r, g, b, id)
	local hour = date("%H");
	local minute = date("%M");
	local second = date("%S");
	local ampm = "오전";
	local new_msg;

	if (not msg) then
		return;
	end

--[[	if (msg and event== "CHAT_MSG_CHANNEL") then
		if (WindChatConfigAll[14]) then
			msg = string.gsub(msg, "^%[(%d+)%. "..string.gsub(arg9, "([^%s]+).*", "%1").."] ", "[%1] ");
		end
	end]]
	if (msg ~= nil) then
		local _, _, _, name = string.find(msg, "(|Hplayer:.-|h%[)([^%]]+)(.+)");
		if name then
			if (WindChatConfigAll[16]) then
				PreFix = WindChat_setNameColor(nil, name)
				LocalEnd = "|r"
			else
				PreFix = ""
				LocalEnd = ""
			end
			if (strsub(event, 1, 13) == "CHAT_MSG_RAID" and WindChatConfigAll[15]) then
				local numRaid = GetNumRaidMembers();
				for i=1, numRaid do
					local n, rank, subgroup, _, class = GetRaidRosterInfo(i);
					if (name == n) then
						local EndFix = ""
						if (class == "사냥꾼") then
							EndFix = EndFix..subgroup.."냥"
						else
							EndFix = EndFix..subgroup..strsub(class, 1, 3)
						end
						msg = string.gsub(msg, "(|Hplayer:.-|h)(%[)([^%]]+)(%])(.+)", "%1" .. PreFix .. "[%3] ["..EndFix.."]"..LocalEnd.."%5");
						break;
					end
				end
			else
				 msg = string.gsub(msg, "(|Hplayer:.-|h)(%[)([^%]]+)(%])(.+)", "%1" .. PreFix .. "[%3]"..LocalEnd.."%5");
			end
		end
	end
	if (msg and WindChatTimeConfig["Wind"..this:GetName()]) then
		new_msg = minute;
		if (WindChatConfigAll[9]) then new_msg = new_msg..":"..second; end
		if (WindChatConfigAll[10]) then
			hour = hour + 0;
			if (hour > 12) then
				hour = hour - 12;
				ampm = "오후";
			else
				if (hour == 12) then
					ampm = "오후";
				else
					ampm = "오전";
				end
			end
			new_msg = ampm.." "..hour..":"..new_msg;
		else
			new_msg = hour..":"..new_msg;
		end
		if (WindChatConfigAll[11]) then
			new_msg = "|cFF"..WindChatConfigAll[12].."["..new_msg.."]".."|r".." "..msg;
		else
			new_msg = "["..new_msg.."]".." "..msg;
		end
		this:Original_AddMessage(new_msg, r, g, b, id);
	else
		this:Original_AddMessage(msg, r, g, b, id);
	end
end
