--------------------------------------------------------------------------------
-- CT_MailModPlus R25 by Bitz (wow.SomeGate.com)
--------------------------------------------------------------------------------

CT_MMINBOX_DELETEDELAY = 1;
CT_MMINBOX_DELETEEVENTDELAY = 1;

CT_MMInbox_SelectedItems = { };

function CT_MMInbox_OnLoad()
	MailItem1:SetPoint("TOPLEFT", "InboxFrame", "TOPLEFT", 48, -80);
	for i = 1, 7, 1 do
		getglobal("MailItem" .. i .. "ExpireTime"):SetPoint("TOPRIGHT", "MailItem" .. i, "TOPRIGHT", 10, -4);
		getglobal("MailItem" .. i):SetWidth(280);
	end
	this.eventFunc = { };
	this:RegisterEvent("MAIL_INBOX_UPDATE");
	this:RegisterEvent("UI_ERROR_MESSAGE");
end

function CT_MMInbox_OnUpdate(elapsed)
	if ( CT_Mail_addItem ) then
		CT_Mail_addItem[4] = CT_Mail_addItem[4] - elapsed;
		if ( CT_Mail_addItem[4] <= 0 ) then
			CT_Mail_addItem = nil;
			for i = 1, NUM_CONTAINER_FRAMES, 1 do
				if ( getglobal("ContainerFrame" .. i):IsVisible() ) then
					ContainerFrame_Update(getglobal("ContainerFrame" .. i));
				end
			end
		end
	end
	if ( not this.returnSelected and this.num and this.elapsed ) then -- modified for Return Selected
		this.elapsed = this.elapsed - elapsed;
		if ( this.elapsed <= 0 ) then
			this.elapsed = nil;
			if ( this.id[1] ) then
				local val = this.id[1];
				local success = CT_MMInbox_PickMail(val, this.openSelected);
				if ( success ~= 2 ) then
					tremove(this.id, 1);
					this.num = this.num - 1;
				end
				if ( success == 1 ) then
					for key, va in pairs(this.id) do
						if ( va > val ) then
							this.id[key] = va-1;
						end
					end
					this.lastVal = val;
					InboxFrame_Update();
				else
					this.elapsed = 1+CT_MMINBOX_DELETEDELAY;
					this.lastVal = nil;
				end
				if ( this.num == 0 ) then
					this.num = nil;
					CT_MMInbox_DisableClicks(nil);
				end
			end
		end
	end
	------- [1] Return Selected Source (from Myzael's) ---------------------------
	if ( this.returnSelected and this.num and this.elapsed ) then
		this.elapsed = this.elapsed - elapsed;
		if ( this.elapsed <= 0 ) then
			this.elapsed = nil;
			if ( this.id[1] ) then
				local val = this.id[1];
				local success = CT_MMInbox_ReturnMail(val, this.returnSelected);
				if ( success ~= 2 ) then
					tremove(this.id, 1);
					this.num = this.num - 1;
				end
				if ( success == 1 ) then
					for key, va in pairs(this.id) do
						if ( va > val ) then
							this.id[key] = va-1;
						end
					end
					this.lastVal = val;
					InboxFrame_Update();
				else
					this.elapsed = 1+CT_MMINBOX_DELETEDELAY;
					this.lastVal = nil;
				end
				if ( this.num == 0 ) then
					this.num = nil;
					CT_MMInbox_DisableClicks(nil);
					this.returnSelected = nil;
				end
			end
		end
	end
	------- End of [1] -----------------------------------------------------------
	if ( this.delete ) then
		this.delete[1] = this.delete[1] - elapsed;
		if ( this.delete[1] <= 0 ) then
			local packageIcon, stationeryIcon, sender, subject, money, CODAmount, daysLeft, itemID, wasRead, wasReturned, textCreated  = GetInboxHeaderInfo(this.delete[2]);
			if ( money == 0 and not itemID ) then
				GetInboxText(this.delete[2]);
				DeleteInboxItem(this.delete[2]);
			end
			this.delete = nil;
			this.elapsed = 0.5+CT_MMINBOX_DELETEDELAY;
		end
	end
end

function CT_MMInbox_OnEvent(event)
	if ( event == "MAIL_INBOX_UPDATE" ) then
		if ( this.eventDelete ) then
			this.delete = { CT_MMINBOX_DELETEEVENTDELAY, this.eventDelete };
			this.eventDelete = nil;
		end
	------- [2] Modified by Bitz -------------------------------------------------
	elseif ( InboxFrame:IsVisible() and not OpenMailFrame:IsVisible() and event == "UI_ERROR_MESSAGE" ) then
	  if ( arg1 == ERR_INV_FULL ) then
	    CT_MMInbox_Abort();
	    if ( GetLocale() == "koKR" ) then
	      CT_MMInbox_Print("우편 받기: 가방이 가득찼습니다. 중지합니다.", 1, 0, 0);
	    else
	      CT_MMInbox_Print("<CTMod> Error: Inventory full. Aborting.", 1, 0, 0);
	    end
	  elseif ( arg1 == ERR_ITEM_MAX_COUNT ) then
   	  if ( GetLocale() == "koKR" ) then
    	  CT_MMInbox_Print("우편 받기: 이미 소유하고 있는 고유 아이템이 있습니다. 건너뜁니다.", 1, 0, 0);
    	else
        CT_MMInbox_Print("<CTMod> Error: You already have the maximum amount of that item. Skipping.", 1, 0, 0);
      end
    	this.elapsed = CT_MMINBOX_DELETEDELAY;
    	if ( this.lastVal ) then
    		for key, va in pairs(this.id) do
    			if ( va >= this.lastVal ) then
    				this.id[key] = va+1;
    			end
    		end
    	end
    end
	end
	------- End of [2] -----------------------------------------------------------
end

function CT_MMInbox_PickMail(id, openSelected)
	if ( not id ) then
		return 0;
	end
	local packageIcon, stationeryIcon, sender, subject, money, CODAmount, daysLeft, hasItem, wasRead, wasReturned, textCreated, canReply = GetInboxHeaderInfo(id);
	if ( CODAmount > 0 ) then
		return 0;
	elseif ( not hasItem and money == 0 and not openSelected ) then
		return 0;
	end
	local eventDelete;
	if ( hasItem ) then
		TakeInboxItem(id);
		eventDelete = 1;
		if ( money > 0 ) then
			return 2;
		end
	end
	if ( money > 0 ) then
		TakeInboxMoney(id);
		eventDelete = 1;
	end
	if ( eventDelete ) then
		CT_MMInboxFrame.eventDelete = id;
	else
		CT_MMInboxFrame.delete = { CT_MMINBOX_DELETEDELAY, id };
	end
	return 1;
end

function CT_MMInbox_SetSelected()
	local id = this:GetID() + (InboxFrame.pageNum-1)*7;
	if ( not this:GetChecked() ) then
		for k, v in pairs(CT_MMInbox_SelectedItems) do
			if ( v == id ) then
				tremove(CT_MMInbox_SelectedItems, k);
				break;
			end
		end
	else
		tinsert(CT_MMInbox_SelectedItems, id);
	end
	------- [3 - 6] by Bitz ------------------------------------------------------
	-- [3] Control Button Status
	if ( getn(CT_MMInbox_SelectedItems) == 0 and not this:GetChecked() ) then
	  CT_MMInboxOpenSelected:Disable();
		CT_MMInboxReturnSelected:Disable();
	else
	  CT_MMInboxOpenSelected:Enable();
		CT_MMInboxReturnSelected:Enable();
	end
  -- [4] Set the Same Items Selected <Part 1>
	local name, itemTexture, count, quality, canUse = GetInboxItem(id);
  if ( IsAltKeyDown() ) then
    if ( not this:GetChecked()) then
      DeselectedItemName = name;
    else
      SelectedItemName = name;
    end
    CT_MMInbox_SetSelectedSameItem(id);
  end
  -- [5] Set All the Items Selected
  if ( IsShiftKeyDown() ) then
    CT_MMInbox_SelectedItems = { };
    if ( not this:GetChecked() ) then
    else
      for i = 1, GetInboxNumItems(), 1 do
        tinsert(CT_MMInbox_SelectedItems, i);
      end
    end
  end
  CT_MMInbox_newInboxFrame_Update();
end

-- [6] Set the Same Items Selected <Part 2>
function CT_MMInbox_SetSelectedSameItem(id)
	for i = 1, GetInboxNumItems(), 1 do
	  local name, itemTexture, count, quality, canUse = GetInboxItem(i);
	  if ( name == SelectedItemName and i ~= id ) then
  	  if ( CT_MMInbox_SelectedItemExist(i) == true ) then
  	  else 
        tinsert(CT_MMInbox_SelectedItems, i);
      end
    elseif ( name == DeselectedItemName and i ~= id) then
      for k, v in pairs(CT_MMInbox_SelectedItems) do
  			if ( v == i ) then
  				tremove(CT_MMInbox_SelectedItems, k);
  				break;
  			end
  		end
    end
  end
  SelectedItemName = nil;
  DeselectedItemName = nil;
  CT_MMInbox_newInboxFrame_Update();
end

function CT_MMInbox_SelectedItemExist(i)
	for k, v in pairs(CT_MMInbox_SelectedItems) do
		if ( v == i ) then
		  return true;
		end
	end
end
------- End of [3 - 6] ---------------------------------------------------------

function CT_MMInbox_OpenSelected()
	CT_MMInbox_DisableClicks(1);
	CT_MMInboxFrame.num = 0;
	CT_MMInboxFrame.elapsed = CT_MMINBOX_DELETEDELAY;
	CT_MMInboxFrame.id = { };
	
	for k, v in pairs(CT_MMInbox_SelectedItems) do
		CT_MMInboxFrame.num = CT_MMInboxFrame.num + 1;
		tinsert(CT_MMInboxFrame.id, v);
	end
	
	CT_MMInboxFrame.numMails = CT_MMInboxFrame.num;
	CT_MMInbox_SelectedItems = { };
end

-- Hook InboxFrame_Update
CT_MMInbox_oldInboxFrame_Update = InboxFrame_Update;
function CT_MMInbox_newInboxFrame_Update()
	CT_MMInbox_oldInboxFrame_Update();
	for i = 1, 7, 1 do
		local index = (i + (InboxFrame.pageNum-1)*7);
		if ( index > GetInboxNumItems() ) then
			getglobal("CT_MailBoxItem" .. i .. "CB"):Hide();
		else
			getglobal("CT_MailBoxItem" .. i .. "CB"):Show();
			------- [7] Show Returned Mark in the Subject (by Bitz) ------------------
			local packageIcon, stationeryIcon, sender, subject, money, CODAmount, daysLeft, hasItem, wasRead, wasReturned, _, _, isGM = GetInboxHeaderInfo(index);
			if ( wasReturned and not isGM) then
				subjectText = getglobal("MailItem"..i.."Subject");
				subjectText:SetText(CT_MMINBOX_RETURNEDMARK..subject);
			end
			-- Change COD Mark
			if ( GetLocale() == "koKR" ) then
				if ( CODAmount > 0 ) then
					getglobal("MailItem"..i.."ButtonCOD"):SetText(CT_MMINBOX_CODMARK);
					getglobal("MailItem"..i.."ButtonCOD"):SetWidth(30)
				end
			end
			-------- End of [7] ------------------------------------------------------
			getglobal("CT_MailBoxItem" .. i .. "CB"):SetChecked(nil);
			for k, v in pairs(CT_MMInbox_SelectedItems) do
				if ( v == index ) then
					getglobal("CT_MailBoxItem" .. i .. "CB"):SetChecked(1);
					break;
				end
			end
		end
	end
	if ( CT_MMInboxFrame.num ) then
		CT_MMInbox_DisableClicks(1, 1);
	end
	------- [8 - 9] by Bitz ------------------------------------------------------
	-- [8] Control Mail Icon & Button Status
	local numItems = GetInboxNumItems();
	local selectedItems = getn(CT_MMInbox_SelectedItems);
	if ( numItems == 0 ) then
	  MiniMapMailFrame:Hide();
	end
	if ( numItems == 0 or selectedItems == 0 ) then
	  CT_MMInboxOpenSelected:Disable();
		CT_MMInboxReturnSelected:Disable();
	end
	-- [9] Show Page Number
	local endpageNum = ceil(numItems/7);
	if ( selectedItems == 0 and numItems > 0 ) then
		selectedItems = " (";
		numItems = numItems..")";
	elseif ( numItems == 0 ) then
		selectedItems = "";
		numItems = "";
	else
		selectedItems = " ("..selectedItems.."/";
		numItems = numItems..")";
	end
	if ( endpageNum == 0 ) then
		endpageNum = 1;
	end
	CT_MMInboxCurrentPage:SetText(InboxFrame.pageNum.." / "..endpageNum..selectedItems..numItems);
	------- End of [8 - 9] -------------------------------------------------------
end

------- [10] Return Selected Source (from Myzael's) ----------------------------
function CT_MMInbox_ReturnMail(id, returnSelected)
	if ( not id ) then
		return 0;
	end
	local packageIcon, stationeryIcon, sender, subject, money, CODAmount, daysLeft, hasItem, wasRead, wasReturned, textCreated, canReply = GetInboxHeaderInfo(id);
  -- [11] added by Bitz
	if ( wasReturned ) then
	  if ( GetLocale() == "koKR" ) then
      CT_MMInbox_Print("우편 반송: 우편물 |c00FFFFFF" .. this.numMails-(this.num-1) .. "|r/|c00FFFFFF" .. this.numMails .. "|r|1은;는; 반송되어 돌아온 우편물이므로 건너뜁니다.", 1, 0, 0);
	  else
	    CT_MMInbox_Print("<CTMod> Mail |c00FFFFFF" .. this.numMails-(this.num-1) .. "|r/|c00FFFFFF" .. this.numMails .. "|r is returned one, skipping.", 1, 0, 0);
	  end
		return 0;
	elseif ( not canReply ) then
	  if ( GetLocale() == "koKR" ) then
	    CT_MMInbox_Print("우편 반송: 우편물 |c00FFFFFF" .. this.numMails-(this.num-1) .. "|r/|c00FFFFFF" .. this.numMails .. "|r|1은;는; 반송할 수 없는 우편물이므로 건너뜁니다.", 1, 0, 0);
	  else
	    CT_MMInbox_Print("<CTMod> Mail |c00FFFFFF" .. this.numMails-(this.num-1) .. "|r/|c00FFFFFF" .. this.numMails .. "|r cannot be returned, skipping.", 1, 0, 0);
	  end
		return 0;
	end
	-- End of [11]
	if ( GetLocale() == "koKR" ) then
	  CT_MMInbox_Print("우편 반송: |c00FFFFFF".. ( sender or "<Unknown Sender>" ) .. "|r에게 \"|c00FFFFFF".. ( subject or "<No Subject>" ) .. "|r\"|1을;를; 반송합니다. (|c00FFFFFF" .. this.numMails-(this.num-1) .. "|r/|c00FFFFFF" .. this.numMails .. "|r)", 1, 1, 0);
	else
	  CT_MMInbox_Print("<CTMod> Returning mail |c00FFFFFF" .. this.numMails-(this.num-1) .. "|r/|c00FFFFFF" .. this.numMails .. "|r: \"|c00FFFFFF" .. ( subject or "<No Subject>" ) .. "|r\" to |c00FFFFFF" .. ( sender or "<Unknown Sender>" ) .. "|r.", 1, 1, 0);
  end
  
	local eventDelete;
  
	ReturnInboxItem(id);
  
	if ( eventDelete ) then
		CT_MMInboxFrame.eventDelete = id;
	else
		CT_MMInboxFrame.delete = { CT_MMINBOX_DELETEDELAY, id };
	end
	return 1;
end

function CT_MMInbox_ReturnSelected()
	CT_MMInbox_DisableClicks(1);
	CT_MMInboxFrame.num = 0;
	CT_MMInboxFrame.elapsed = CT_MMINBOX_DELETEDELAY;
	CT_MMInboxFrame.id = { };
	CT_MMInboxFrame.returnSelected = 1;
    
    for k, v in pairs(CT_MMInbox_SelectedItems) do
        CT_MMInboxFrame.num = CT_MMInboxFrame.num + 1;
        tinsert(CT_MMInboxFrame.id, v);
    end
  
	CT_MMInboxFrame.numMails = CT_MMInboxFrame.num;
	CT_MMInbox_SelectedItems = { };
end
------- End of [10] ------------------------------------------------------------

InboxFrame_Update = CT_MMInbox_newInboxFrame_Update;
CT_MMInbox_oldInboxFrame_OnClick = InboxFrame_OnClick;
function CT_MMInbox_DisableClicks(disable, loopPrevention)
	if ( disable ) then
		for i = 1, 7, 1 do
			getglobal("MailItem" .. i .. "ButtonIcon"):SetDesaturated(1);
		end
		InboxFrame_OnClick = function() this:SetChecked(nil) end;
	else
		for i = 1, 7, 1 do
			getglobal("MailItem" .. i .. "ButtonIcon"):SetDesaturated(nil);
		end
		if ( not loopPrevention ) then
			InboxFrame_Update();
		end
		InboxFrame_OnClick = CT_MMInbox_oldInboxFrame_OnClick;
	end
end

function CT_MMInbox_Abort()
	CT_MMInboxFrame.num = nil;
	CT_MMInboxFrame.elapsed = nil;
	CT_MMInboxFrame.id = { };
	CT_MMInbox_SelectedItems = { };
	CT_MMInbox_DisableClicks();
end

function CT_MMInbox_Print(msg, r, g, b)
	DEFAULT_CHAT_FRAME:AddMessage(msg, r, g, b);
end

CT_MMInbox_oldCloseMail = CloseMail;
function CT_MMInbox_newCloseMail()
	CT_MMInbox_oldCloseMail();
	CT_MMInbox_Abort();
	StaticPopup_Hide("CT_MAIL_RETURN_CONFIRMATION");
	StaticPopup_Hide("CT_MAIL_ADDSENDEE_CONFIRMATION");
	StaticPopup_Hide("CT_MAIL_RESETSENDEES_CONFIRMATION");
	for i = 1, NUM_CONTAINER_FRAMES, 1 do
		if ( getglobal("ContainerFrame" .. i):IsVisible() ) then
			ContainerFrame_Update(getglobal("ContainerFrame" .. i));
		end
	end
end
CloseMail = CT_MMInbox_newCloseMail;

CT_MMInbox_oldTakeInboxItem = TakeInboxItem;
function CT_MMInbox_newTakeInboxItem(id)
	CT_MMInbox_oldTakeInboxItem(id);
	local name, itemTexture, count, quality, canUse = GetInboxItem(id);
	tinsert(CT_MMForwardFrame.pickItem, name);
end
TakeInboxItem = CT_MMInbox_newTakeInboxItem;

local oldSMMfunc = SendMailMoney.onvalueChangedFunc;
SendMailMoney.onvalueChangedFunc = function()
	if ( oldSMMfunc ) then
		oldSMMfunc();
	end
	local subject = SendMailSubjectEditBox:GetText();
	if ( subject == "" or string.find(subject, "^%[%d+G, %d+S, %d+C%]$") or string.find(subject, "^%d+골드, %d+실버, %d+코퍼$")) then
		local copper, silver, gold = SendMailMoneyCopper:GetText(), SendMailMoneySilver:GetText(), SendMailMoneyGold:GetText();
		if ( not tonumber(copper) ) then
			copper = 0;
		end
		if ( not tonumber(silver) ) then
			silver = 0;
		end
		if ( not tonumber(gold) ) then
			gold = 0;
		end
		if ( copper + silver + gold > 0 ) then
		  if ( GetLocale() == "koKR" ) then
			  SendMailSubjectEditBox:SetText(format("%s골드, %s실버, %s코퍼", gold, silver, copper));
			else
			  SendMailSubjectEditBox:SetText(format("[%sG, %sS, %sC]", gold, silver, copper));
			end
		end
	end
end

-- [12] Confirmation Popup Dialog by Bitz
StaticPopupDialogs["CT_MAIL_RETURN_CONFIRMATION"] = {
	text = TEXT(CT_MMINBOX_RETURN_CONFIRMATION_TEXT),
	button1 = TEXT(YES),
	button2 = TEXT(NO),
	OnAccept = function()
		CT_MMInbox_ReturnSelected();
	end,
	OnShow = function()
		CT_MMInboxOpenSelected:Disable();
		for i = 1, 7, 1 do
			getglobal("CT_MailBoxItem"..i.."CB"):Disable();
			getglobal("MailItem"..i.."Button"):Disable();
		end
	end,
	OnHide = function()
		CT_MMInboxOpenSelected:Enable();
		for i = 1, 7, 1 do
			getglobal("CT_MailBoxItem"..i.."CB"):Enable();
			getglobal("MailItem"..i.."Button"):Enable();
		end
	end,
	timeout = 0,
	hideOnEscape = 1,
};
-- End of [12]
