-- SELECTED_CHAT_FRAME:AddMessage("MT: "..msg, 0.0, 0.9, 0.9)
local _G = getfenv(0)
local f = CreateFrame("Frame")

f:RegisterEvent("VARIABLES_LOADED")
f:RegisterEvent("PLAYER_ENTERING_WORLD")
f:SetScript("OnEvent", function(_, event)
	if (event == "VARIABLES_LOADED") then 
	  SCM_ChatFade(); 
	  SCM_OnLoad();
	end 
end)
-- =================================================================================
-- 기본 설정값 --
-- =================================================================================
SCMSaved= {
  enableWheel=     true;  -- 마우스 휠 스크롤 기능
  chatFade=        false; -- 대화내용 숨김 (일정시간 동안 새로운 내용이 없을결루 해당 대화창을 숨깁니다.)
---------------- 위까진 메뉴설정, 아래는 직접 수정 ( true or false ) ---------------
  MoveEditBox=     false;  -- 대화입력창 위로 표시 (true=위,false=아래)
  FadeMenuButton=  true; -- 메뉴버튼 숨김
  shortChannels=   true;  -- 짧은 채널명 (예. [1] 기존 [1. 공개]) 
};

if SCMChatDB==nil then SCMChatDB = {}; end  
if SCMChatDB["Head"] == nil then  SCMChatDB["Head"] = ""; end
if SCMChat==nil then  SCMChat = {};  end 	
if SCMChat["CallMe"] == nil then  SCMChat["CallMe"] = {}; end
	
local function print(msg)
  DEFAULT_CHAT_FRAME:AddMessage(msg);
end;
    
-- =================================================================================
-- 대화 입력창 이동
-- =================================================================================
do
	for i =1, 10 do
  local eb = _G[format("%s%d%s", "ChatFrame", i, "EditBox")] -- ChatFrameEditBox
  local cf = _G[format("%s%d", "ChatFrame", i)]
  if (SCMSaved.MoveEditBox == true) then
  	eb:ClearAllPoints()
	eb:SetPoint("BOTTOMLEFT",  cf, "TOPLEFT",  -5, 0)
	eb:SetPoint("BOTTOMRIGHT", cf, "TOPRIGHT", 5, 0)
  elseif (SCMSaved.MoveEditBox == false) then
	eb:ClearAllPoints()
	eb:SetPoint("TOPLEFT",  cf, "BOTTOMLEFT",  -5, 0)
	eb:SetPoint("TOPRIGHT", cf, "BOTTOMRIGHT", 5, 0)
  end; 

-- =================================================================================
--  알트 클릭 초대
-- =================================================================================
--[[hooksecurefunc("SetItemRef", function(link)
    if IsAltKeyDown() and link then
	local name = link:match("^player:([^:]+).*$")
	if name then InviteUnit(name) eb:Hide() end 
    end
end)]]
local origSetItemRef = SetItemRef
SetItemRef = function(link, text, button)
	local linkType = string.sub(link, 1, 6)
	if IsAltKeyDown() and linkType == "player" then
		local name = string.match(link, "player:([^:]+)")
		InviteUnit(name)
		return nil
	end
	return origSetItemRef(link,text,button)
end

-- =================================================================================
-- 방향키 기능 추가 
-- =================================================================================
        eb:SetAltArrowKeyMode(false)  
  end
end

-- =================================================================================
-- 채널 고정 기능 추가
-- =================================================================================
ChatTypeInfo["CHANNEL"].sticky = 1; --채널대화
ChatTypeInfo["OFFICER"].sticky = 1; --공대 오피서
ChatTypeInfo["RAID_WARNING"].sticky = 1; --공대 경보
ChatTypeInfo["WHISPER"].sticky 	= 1;  -- 귓속말

function SCM_OnLoad()
-- =================================================================================
-- 추가 슬래쉬 명령어
-- =================================================================================
  SlashCmdList["SCM"]= SCM_Command;
  SLASH_SCM1= "/scm";
  SLASH_SCM2= "/sc";
  SlashCmdList["CALCULATOR"] = function(msg) Calculator(msg) end
  SLASH_CALCULATOR1="/계산";
  SLASH_CALCULATOR2="//";
  --SlashCmdList["SCMH"] = SCM_SetHead;
  --SLASH_SCMH1 = "/말머리";
  --SlashCmdList["SCMCM"] = SCMCM_Set;
  --SLASH_SCMCM1 = "/나를불러주세요";
 -- SLASH_SCMCM2 = "/callme";
-- =================================================================================  
-- 귓속말 표시 설정
-- =================================================================================
  SCM_CUSTOM_CHT_FROM				= "<FR>%s:\32"; --귓속말 받음 표시
  SCM_CUSTOM_CHT_TO				= "<To>%s:\32"; --귓속말 보냄 표시
  SCM_CUSTOM_CHT_YELL                             = "[Y]%s:\32"; --외침 표시
  print(NORMAL_FONT_COLOR_CODE.."SisterChatMods"..FONT_COLOR_CODE_CLOSE.." 불러옴. "..NORMAL_FONT_COLOR_CODE.."/sc"..FONT_COLOR_CODE_CLOSE.." : 명령어 출력. ("..NORMAL_FONT_COLOR_CODE.."자매"..FONT_COLOR_CODE_CLOSE..",노르간논)");
end;


-- =================================================================================
-- SisterChatMods 명령어
-- =================================================================================
function SCM_Command(msg)
  local cs= NORMAL_FONT_COLOR_CODE;
  local ce= FONT_COLOR_CODE_CLOSE;
  local header= cs.."SisterChatMods: "..ce;
  if (msg == "") then
    print(header.."설정을 위한 명령어들 입니다.:");
    print(cs.."/sc 채널"..ce.." 채널명 표시 형식 전환");
    print(cs.."/sc 휠"..ce.."  마우스 휠 스크롤 On/Off");
    print(cs.."/sc 지속"..ce.." 대화 지속 On/Off\n         '일정시간 후 대화내용이 숨겨짐을 방지합니다.'");
    print(cs.."/sc 입력창"..ce.." 대화 입력창 위/아래 전환");
    print(cs.."/tt or /ㅅㅅ"..ce.." 대상에게 귓속말");
    --print(cs.."/말머리 내용"..ce.." 말머리 설정");
    --print(cs.."/나를불러주세요"..ce.." 나를불러주세요 설정");
    print(cs.."/해산"..ce.." 공격대 해산 '공격대장만 이용가능'");
    print(cs.."/파탈"..ce.." 파티 탈퇴");
    print(cs.."/계산 '수식'"..ce.." 간단한 계산기");
   -- print(cs.."/전체승급"..ce.." 공대원 전체 부공대장으로 승급(본인이 공대장일 경우)");
  elseif (msg == "채널") then
      print(header.."sisterchatmods.lua파일을 메모장 등으로 불러낸 후\n                     shortChannels=true 값을 false로 수정 저장 후 리로드");
  elseif (msg == "휠") then
    if (SCMSaved.enableWheel) then
      print(header.."마우스 휠 스크롤 끔");
      SCMSaved.enableWheel= false;
    else
      print(header.."마우스 휠 스크롤 켬");
      SCMSaved.enableWheel= true;
    end;
  elseif (msg == "지속") then
    if (SCMSaved.chatFade) then
      print(header.."대화 지속 기능 켬.");
      SCMSaved.chatFade= false;
      SCM_ChatFade()
    else
      print(header.."대화 지속 기능 끔 - 2분 동안 새글이 없으면 해당 대화창의 대화내용을 숨깁니다.");
      SCMSaved.chatFade= true;
      SCM_ChatFade()
    end
  elseif (msg == "입력창") then
      print(header.."sisterchatmods.lua파일을 메모장 등으로 불러낸 후\n                     MoveEditBox=true 값을 false로 수정 저장 후 리로드");
  end;
end;

-- =================================================================================
-- 대화 지속 
-- =================================================================================
function SCM_ChatFade()
	for i = 1, 10 do
		local chatframe = getglobal("ChatFrame"..i);
		chatframe:SetFading(SCMSaved.chatFade);
	end
end



-- =================================================================================
-- "/해산" : 공대 해산 
-- =================================================================================

local function RaidDisband()
	if IsRaidLeader() then
		local pName = UnitName("player")
		SendChatMessage("모두 수고하셨습니다.", "RAID")
		for i = 1, GetNumRaidMembers() do
			local name, _, _, _, _, _, _, online = GetRaidRosterInfo(i)
			if online and name ~= pName then
				UninviteUnit(name)
			end
		end
		LeaveParty()
	else
		DEFAULT_CHAT_FRAME:AddMessage("|cff88ffaa당신은 공대장이 아닙니다. 해산할 수 없습니다.")
	end
end

SLASH_RaidDisband1 = "/해산"
SlashCmdList.RaidDisband = RaidDisband

-- =================================================================================
-- '/파탈' 파티탈퇴
-- =================================================================================
local function Party(cmd)
  LeaveParty()
end

SlashCmdList["CANParty"] = function(cmd)
  Party(cmd);
end

SLASH_CANParty1 = "/파탈";

-- =================================================================================
-- Clear ChatFrame : 모든 채팅창 내용 지우기 (전투로그 제외)
-- =================================================================================
local function ClearChatFrame(cmd)
  local cf;
     for i = 1, NUM_CHAT_WINDOWS do
       if i~=2 then               -- Skip Combatlog
          cf = getglobal("ChatFrame"..i);
          if( (cf ~= nil)) then
            cf:Clear();
          end
       end
    end
end

SlashCmdList["ClearChat"] = function(cmd)
	ClearChatFrame(cmd);
end

SLASH_ClearChat1 = "/cls";
SLASH_ClearChat2 = "/친";

-- =================================================================================
-- More Font Size : 폰트 크기 세부 설정
-- =================================================================================
CHAT_FONT_HEIGHTS = {
    [1] = 7,     [2] = 8,    [3] = 9,    [4] = 10,    [5] = 11,    [6] = 12,    [7] = 13,    [8] = 14,    [9] = 15,    [10] = 16,
    [11] = 17,    [12] = 18,    [13] = 19,    [14] = 20,    [15] = 21,    [16] = 22,    [17] = 24,    [18] = 32
}

-- =================================================================================
-- 마우스 휠 사용 및 추가기능
-- =================================================================================
 
hooksecurefunc('FloatingChatFrame_OnMouseScroll', function(self, dir)
	if dir > 0 then
		if IsShiftKeyDown() then
			self:ScrollToTop()
		elseif IsControlKeyDown() then
			--only need to scroll twice because of blizzards scroll
			self:ScrollUp()
			self:ScrollUp()
			self:ScrollUp()
		end
	elseif dir < 0 then
		if IsShiftKeyDown() then
			self:ScrollToBottom()
		elseif IsControlKeyDown() then
			--only need to scroll twice because of blizzards scroll
			self:ScrollDown()
			self:ScrollDown()
			self:ScrollDown()
		end
	end
end)

-- =================================================================================
-- 버튼 숨김, 맨아래로 버튼
-- =================================================================================

local function Hide(f)
	f:SetScript('OnShow', f.Hide)
	f:Hide()
end

--[[ Moving Buttons ]]--

local function UpdateBottomButton(frame)
	local button = frame.buttonFrame.bottomButton
	if frame:AtBottom() then
		button:Hide()
	else
		button:Show()
	end
end

local function OnClick(button)
	UpdateBottomButton(button:GetParent():GetParent())
end

hooksecurefunc('FloatingChatFrame_OnMouseScroll', UpdateBottomButton)
for i= 1,10 do
	local frame = _G['ChatFrame'..i]
	frame:HookScript('OnShow', UpdateBottomButton)
	
	local buttons = frame.buttonFrame
	buttons:DisableDrawLayer('BACKGROUND')
	buttons:DisableDrawLayer('BORDER')
	
	local bottom = buttons.bottomButton
	bottom:SetPoint('BOTTOMRIGHT', frame, 'BOTTOMRIGHT')
	bottom:HookScript('OnClick', OnClick)
	bottom:SetAlpha(.6)
	bottom:SetScale(.7)
	
	Hide(buttons.upButton)
	Hide(buttons.downButton)
	UpdateBottomButton(frame)
	frame:SetClampRectInsets(0,0,0,0) --Allow the chat frame to move to the end of the screen
end

Hide(ChatFrameMenuButton)
Hide(FriendsMicroButton)



-- =================================================================================
--  채널줄임
-- =================================================================================
local _G = getfenv(0)
_G.CHAT_GUILD_GET =                 "[G] %s:\32"
_G.CHAT_RAID_GET =                  "[R] %s:\32"
_G.CHAT_PARTY_GET =                 "[P] %s:\32"
_G.CHAT_PARTY_LEADER_GET =          "[PL] %s:\32"
_G.CHAT_PARTY_GUIDE_GET =	    "[DG] %s:\32" --3.3.2 던전가이드 추가
_G.CHAT_RAID_WARNING_GET =          "|cffff0000[|r[RW]|cffff0000]|r %s:\32"
_G.CHAT_RAID_LEADER_GET =           "|cffff3399[|r[RL]|cffff3399]|r %s:\32"
_G.CHAT_OFFICER_GET =               "[O] %s:\32"
_G.CHAT_BATTLEGROUND_GET =          "[BG] %s:\32"
_G.CHAT_BATTLEGROUND_LEADER_GET =   "|cffff0000[|r[BL]|cffff0000]|r %s:\32"
_G.CHAT_SAY_GET =                   "%s:\32"
_G.CHAT_YELL_GET =                  "[Y] %s:\32"
_G.CHAT_WHISPER_GET =               "[FR] %s:\32"
_G.CHAT_WHISPER_INFORM_GET =        "[To] %s:\32"
_G.CHAT_FLAG_AFK =                  "[비움] "
_G.CHAT_FLAG_DND =                  "[용무중] "
_G.CHAT_FLAG_GM =                   "[GM] "  

-- =================================================================================
--URL 링크 복사
-- =================================================================================
local currentLink = nil
local ref = _G["SetItemRef"]

local gsub = _G.string.gsub
local ipairs = _G.ipairs
local pairs = _G.pairs
local fmt = _G.string.format
local sub = _G.string.sub

local tlds = {COM = true,UK = true,NET = true,INFO = true,CO = true,DE = true,FR = true,ES = true,BE = true,CC = true,US = true,KO = true,CH = true,TW = true,}
local style = "|cffFFFF00|Hurl:%s|h[%s]|h|r"
local tokennum, matchTable = 1, {}
local function RegisterMatch(text)
	local token = "\255\254\253"..tokennum.."\253\254\255"
	matchTable[token] = strreplace(text, "%", "%%")
	tokennum = tokennum + 1
	return token
end
local function Link(link, ...)
	if not link then
		return ""
	end
	return RegisterMatch(fmt(style, link, link))
end
local function Link_TLD(link, tld, ...)
	if not link or not tld then
		return ""
	end
	if tlds[strupper(tld)] then
        return RegisterMatch(fmt(style, link, link))
    else
        return RegisterMatch(link)
    end
end

local patterns = {
		-- X://Y url
	{ pattern = "(%a+://%S+)", matchfunc=Link},
	{ pattern = "%f[%S](%a[%w%.+-]+://%S+)", matchfunc=Link},
		-- www.X.Y url
	{ pattern = "(www%.[%w_-%%]+%.%S+)", matchfunc=Link},
	{ pattern = "%f[%S](www%.[%w_-%%]+%.%S+)", matchfunc=Link},
		-- X@Y.Z email
	{ pattern = "(%S+@[%w_-%%%.]+%.(%a%a+))", matchfunc=Link_TLD},
		-- X.Y.Z/WWWWW url with path
	{ pattern = "^([%w_-%%%.]+[%w_-%%]%.(%a%a+)/%S+)", matchfunc=Link_TLD},
	{ pattern = "%f[%S]([%w_-%%%.]+[%w_-%%]%.(%a%a+)/%S+)", matchfunc=Link_TLD},
		-- X.Y.Z url
	{ pattern = "([%w_-%%%.]+[%w_-%%]%.(%a%a+))", matchfunc=Link_TLD},
	{ pattern = "%f[%S]([%w_-%%%.]+[%w_-%%]%.(%a%a+))", matchfunc=Link_TLD},
}

local function filterFunc(self, event, msg, ...)
	for _, v in ipairs(patterns) do
		msg = gsub(msg, v.pattern, v.matchfunc)
	end
	for k,v in pairs(matchTable) do
		msg = gsub(msg, k, v)
		matchTable[k] = nil
	end
	return false, msg, ...
end

local function AddEvents()
	local events = {
		"CHAT_MSG_CHANNEL", "CHAT_MSG_YELL",
		"CHAT_MSG_GUILD", "CHAT_MSG_OFFICER",
		"CHAT_MSG_PARTY", "CHAT_MSG_RAID",
		"CHAT_MSG_RAID_LEADER",
		"CHAT_MSG_SAY", "CHAT_MSG_WHISPER",
	}
	for _,event in ipairs(events) do
		ChatFrame_AddMessageEventFilter(event, filterFunc)
	end
end
AddEvents()

local function SetItem(link, ...)
	if sub(link, 1, 3) == "url" then
		currentLink = sub(link, 5)
		StaticPopup_Show("BCMUrlCopyDialog")
		return
	end
	return ref(link, ...)
end
_G["SetItemRef"] = SetItem
-- =================================================================================
-- URL 팝업 박스
-- =================================================================================
StaticPopupDialogs["BCMUrlCopyDialog"] = {
	text = "URL",
	button2 = TEXT(CLOSE),
	hasEditBox = 1,
	hasWideEditBox = 1,
	showAlert = 1,
	OnShow = function(self)
		local editBox = _G[self:GetName().."EditBox"]
		editBox:SetWidth(360)
		editBox:SetText(currentLink)
		editBox:SetFocus()
		editBox:HighlightText(0)
		local button = _G[self:GetName().."Button2"]
		button:ClearAllPoints()
		button:SetWidth(200)
		button:SetPoint("CENTER", editBox, "CENTER", 0, -30)
		_G[self:GetName().."AlertIcon"]:Hide()
	end,
	EditBoxOnEscapePressed = function(self) self:GetParent():Hide() end,
	timeout = 0,
	whileDead = 1,
	hideOnEscape = 1,
}

-- =================================================================================
-- 계산기
-- =================================================================================
function Calculator(msg)
	local origHandler = geterrorhandler()
	seterrorhandler(function (msg)
		print("잘못된 계산식입니다.")
	end)
	msg = "local answer="..msg..";if answer then SendChatMessage(\"계산: "..msg.."\",\"SAY\");SendChatMessage(\"결과: \"..answer,\"SAY\") end"
	RunScript(msg)
	seterrorhandler(origHandler)
end
-- =================================================================================
-- 타겟 귓속말 /tt or /ㅅㅅ
-- =================================================================================

local function tellTarget(s)
  if not UnitExists('target') and UnitName('target') and UnitIsPlayer('target') and GetDefaultLanguage('player') == GetDefaultLanguage('target') or not (s and s:len()>0) then
    return
  end
local name, realm = UnitName('target')
  if realm and realm ~= GetRealmName() then
      name = ('%s-%s'):format(name, realm)
  end
SendChatMessage(s, 'WHISPER', nil, name)
end

SlashCmdList['TELLTARGET'] = tellTarget
SLASH_TELLTARGET1 = '/tt'
SLASH_TELLTARGET2 = '/ㅅㅅ'

