
------------------------------
--      Are you local?      --
------------------------------

local L = AceLibrary("AceLocale-2.2"):new("FuBar_Mail")
local Tablet = AceLibrary("Tablet-2.0")
local Dewdrop = AceLibrary("Dewdrop-2.0")

local pendmail, checked
local files = {
	iconnomail = "Interface\\AddOns\\FuBar_MailFu\\nomail.tga",
	iconnew = "Interface\\AddOns\\FuBar_MailFu\\newmail.tga",
	iconAH = "Interface\\AddOns\\FuBar_MailFu\\auction.tga",
	soundpath = "Interface\\AddOns\\FuBar_MailFu\\mail.wav",
}


----------------------------
--      Localization      --
----------------------------

L:RegisterTranslations("enUS", function() return {
	["No mail"] = true,
	["New Mail"] = true,
	["AH Alert!"] = true,

	["New Mail Received (%d/%d)"] = true,

	ttnew = " new mail items",
	tttotal = " total mail items",

	OUTBID = "Outbid: ",
	WON = "Won: ",
	EXPIRED = "Expired: ",
	REMOVED = "Cancelled: ",
	SOLD = "Sold: ",

	minimap = true,
	["Default Minimap"] = true,
	["Show Blizzard's minimap icon"] = true,

	chat = true,
	["Chat Alert"] = true,
	["Print a chat message when mail is received"] = true,

	sound = true,
	["Use Sound"] = true,
	["Play a sound when mail is received"] = true,

	textformat = true,
	["Text Format"] = true,
	["Bar text formatting"] = true,
	both = true,
	number = true,
	text = true,

	["New"] = true,
	["Total"] = true,
} end)


L:RegisterTranslations("koKR", function() return {
	["No mail"] = "우편물 없음",
	["New Mail"] = "신규 우편",
	["AH Alert!"] = "경매장 우편 경고",

	["New Mail Received (%d/%d)"] = "새로운 우편 (%d/%d)",

	ttnew = " 신규 우편 아이템",
	tttotal = " 총 우편 아이템",

	OUTBID = "상회 입찰: ",
	WON = "경매 낙찰: ",
	EXPIRED = "경매 만료: ",
	REMOVED = "경매 취소: ",
	SOLD = "경매 낙찰: ",

	["Default Minimap"] = "기본 미니맵",
	["Show Blizzard's minimap icon"] = "WoW 기본 미니맵 아이콘 표시",

	["Chat Alert"] = "대화창 경고",
	["Print a chat message when mail is received"] = "우편이 도착하면 대화창에 메세지를 출력합니다",

	["Use Sound"] = "경고음 사용",
	["Play a sound when mail is received"] = "우편 도착시 경고음을 재생합니다.",

	["Text Format"] = "텍스트 형식",
	["Bar text formatting"] = "바 텍스트 형식",

	["New"] = "신규",
	["Total"] = "총합",
} end)


L:RegisterTranslations("frFR", function() return {
	["No mail"] = "Aucun courrier",
	["New Mail"] = "Nouveau courrier",
	["AH Alert!"] = "Alerte AH!",
	
	["New Mail Received (%d/%d)"] = "Nouveau courrier re\195\167u (%d/%d)",

	ttnew = " nouveaux courriers d'objets",
	tttotal = " courriers d'objets au total",

	OUTBID = "Surench\195\169rit: ",
	WON = "Gagn\195\169: ",
	EXPIRED = "Expir\195\169: ",
	REMOVED = "Annul\195\169: ",
	SOLD = "Vendu: ",

	minimap = "Mini-carte",
	["Default Minimap"] = "Minicarte par d\195\169faut",
	["Show Blizzard's minimap icon"] = "Afficher l'ic\195\180ne Blizzard sur la mini-carte",

	chat = "chat",
	["Chat Alert"] = "Alerter dans le Chat",
	["Print a chat message when mail is received"] = "Afficher un message dans le chat quand un courrier est re\195\167u",

	sound = "son",
	["Use Sound"] = "Activer les sons",
	["Play a sound when mail is received"] = "Jouer un son quand un courrier est re\195\167u",

	textformat = "FormatTexte",
	["Text Format"] = "Format du texte",
	["Bar text formatting"] = "Formattage de la barre de texte",
	both = "les deux",
	number = "nombre",
	text = "texte",

	["New"] = "Nouveau",
	["Total"] = "Total",
} end)


L:RegisterTranslations("deDE", function() return {
	["No mail"] = "Keine Post ",
	["New Mail"] = "Neue Post ",
	["AH Alert!"] = "AH-Alarm! ",

	["New Mail Received (%d/%d)"] = "Neue Post erhalten (%d/%d)",

	ttnew = " neue Nachrichten",
	tttotal = " Nachrichten insgesamt",

	OUTBID = "\195\156berboten: ",
	WON = "Gewonnen: ",
	EXPIRED = "Abgelaufen: ",
	REMOVED = "Abgebrochen: ",
	SOLD = "Verkauft: ",

	["Chat Alert"] = "Chat-Alarm",
	["Use Sound"] = "Sound verwenden",
} end)

L:RegisterTranslations("esES", function() return {
	["No mail"] = "Sin correo",
	["New Mail"] = "Carta Nueva",
	["AH Alert!"] = "Alerta de la Casa de Subastas!",

	["New Mail Received (%d/%d)"] = "Se ha recibido una nueva carta (%d/%d)",

	ttnew = " nuevos objetos de correo",
	tttotal = " objetos de correo totales",

	OUTBID = "Superado: ",
	WON = "Ganado: ",
	EXPIRED = "Expirado: ",
	REMOVED = "Cancelado: ",
	SOLD = "Vendido: ",

	minimap = "minimapa",
	["Default Minimap"] = "Minimapa por Defecto",
	["Show Blizzard's minimap icon"] = "Muestra el icono del minimapa de Blizzard",

	chat = "chat",
	["Chat Alert"] = "Alerta de Chat",
	["Print a chat message when mail is received"] = "Muestra un mensaje en el chat cuando recibes correo nuevo",

	sound = "sonido",
	["Use Sound"] = "Usar sonido",
	["Play a sound when mail is received"] = "Reproduce un sonido cuando se recibe nuevo correo",

	textformat = "formatodetexto",
	["Text Format"] = "Formato de Texto",
	["Bar text formatting"] = "Formato de la barra de texto",
	both = "ambos",
	number = "n\195\186mero",
	text = "texto",

	["New"] = "Nuevo",
	["Total"] = "Total",
} end)

L:RegisterTranslations("zhTW", function() return {
   ["No mail"] = "無郵件",
   ["New Mail"] = "新郵件",
   ["AH Alert!"] = "競標警戒",

   ["New Mail Received (%d/%d)"] = "收到新的郵件 (%d/%d)",

   ttnew = "新的郵件物品",
   tttotal = "所有郵件物品",

   OUTBID = "出價被超過: ",
   WON = "贏取: ",
   EXPIRED = "拍賣到期: ",
   REMOVED = "拍賣取消: ",
   SOLD = "賣出: ",

   minimap = "迷你地圖信件圖標",
   ["Default Minimap"] = "預設迷你地圖信件圖標",
   ["Show Blizzard's minimap icon"] = "顯示Blizzard's迷你地圖信件圖標",

   chat = "聊天窗口",
   ["Chat Alert"] = "聊天窗口提示",
   ["Print a chat message when mail is received"] = "當確認有郵件時將在聊天窗提示",

   sound = "聲音",
   ["Use Sound"] = "聲音提示",
   ["Play a sound when mail is received"] = "當確認有郵件時將在聲音提示",

   textformat = "文字顯示",
   ["Text Format"] = "顯示模式",
   ["Bar text formatting"] = "Fubar顯示模式",
   both = "文字與數量",
   number = "數量提示",
   text = "文字提示",

   ["New"] = "新的",
   ["Total"] = "總計",
} end)

L:RegisterTranslations("zhCN", function() return {
   ["No mail"] = "无邮件",
   ["New Mail"] = "新邮件",
   ["AH Alert!"] = "竞标警告",

   ["New Mail Received (%d/%d)"] = "收到新的邮件 (%d/%d)",

   ttnew = "新的邮件物品",
   tttotal = "所有邮件物品",

   OUTBID = "出价被超过: ",
   WON = "赢取: ",
   EXPIRED = "拍卖到期: ",
   REMOVED = "拍卖取消: ",
   SOLD = "卖出: ",

   minimap = "小地图邮件图标",
   ["Default Minimap"] = "默认小地图邮件图标",
   ["Show Blizzard's minimap icon"] = "显示暴雪默认的小地图邮件图标",

   chat = "聊天窗口",
   ["Chat Alert"] = "聊天窗口提示",
   ["Print a chat message when mail is received"] = "当有新邮件时将在聊天窗口提示",

   sound = "声音",
   ["Use Sound"] = "声音提示",
   ["Play a sound when mail is received"] = "当有新邮件时使用提示声音",

   textformat = "文字显示",
   ["Text Format"] = "文本格式",
   ["Bar text formatting"] = "FuBar文本格式",
   both = "文字与数量",
   number = "数量提示",
   text = "文字提示",

   ["New"] = "新的",
   ["Total"] = "总计",
} end)

-------------------------------------
--      Namespace Declaration      --
-------------------------------------

FuBar_Mail = AceLibrary("AceAddon-2.0"):new("AceEvent-2.0", "AceConsole-2.0", "AceDB-2.0", "FuBarPlugin-2.0", "AceHook-2.1")
FuBar_Mail.hideWithoutStandby = true
FuBar_Mail.hasIcon = files.iconnomail
FuBar_Mail:RegisterDB("FuBar_MailDB", "FuBar_MailDBPC")
FuBar_Mail:RegisterDefaults("char", {new = 0, total = 0})
FuBar_Mail:RegisterDefaults("profile", {
	playsounds = true,
	showminimap = false,
	chatalerts = true,
	textformat = L.both,
	showtext = true,
	showcount = true,
})
local opts = {type = "group", handler = FuBar_Mail, args = {
	[L.minimap] = {
		type = "toggle", name = L["Default Minimap"], desc = L["Show Blizzard's minimap icon"], order = 1,
		get = function() return FuBar_Mail.db.profile.showminimap end, set = function(v) FuBar_Mail.db.profile.showminimap = v end,
	},
	[L.sound] = {
		type = "toggle", name = L["Use Sound"], desc = L["Play a sound when mail is received"], order = 1,
		get = function() return FuBar_Mail.db.profile.playsounds end, set = function(v) FuBar_Mail.db.profile.playsounds = v end,
	},
	[L.chat] = {
		type = "toggle", name = L["Chat Alert"], desc = L["Print a chat message when mail is received"], order = 1,
		get = function() return FuBar_Mail.db.profile.chatalerts end, set = function(v) FuBar_Mail.db.profile.chatalerts = v end,
	},
	[L.textformat] = {
		type = "text",
		name = L["Text Format"],
		desc = L["Bar text formatting"],
		get = function() return FuBar_Mail.db.profile.textformat end,
		set = function(v) FuBar_Mail.db.profile.textformat = v; FuBar_Mail:Update() end,
		validate = {L["text"], L["number"], L["both"]},
		disabled = function() return not FuBar_Mail:IsTextShown() end,
	},

}}
FuBar_Mail:RegisterChatCommand({"/mailfu"}, opts)
FuBar_Mail.OnMenuRequest = opts


---------------------------
--      Ace Methods      --
---------------------------

function FuBar_Mail:OnEnable()
	pendmail = 0

	self:RegisterEvent("SpecialEvents_MailReceived")
	self:RegisterEvent("SpecialEvents_AHAlert")
	self:RegisterEvent("SpecialEvents_MailInit", "Update")
	self:RegisterEvent("AceEvent_FullyInitialized", "Update")

	self:RegisterEvent("MAIL_SHOW")
	self:RegisterEvent("MAIL_INBOX_UPDATE")
	self:Hook(MiniMapMailFrame, "Show", "MMMailShow", true)
	if not self.db.profile.showminimap and MiniMapMailFrame:IsVisible() then MiniMapMailFrame:Hide() end
end


function FuBar_Mail:MMMailShow(object)
	if self.db.profile.showminimap then return self.hooks[object].Show(object) end
end


function FuBar_Mail:MAIL_SHOW()
	checked = true
	self.db.char.ahalerts = nil
	self:Update()
end


function FuBar_Mail:MAIL_INBOX_UPDATE()
	self.db.char.new = 0
	self.db.char.total = GetInboxNumItems()
	self:Update()
end


function FuBar_Mail:SpecialEvents_MailReceived()
	if not messagenum then messagenum = 1 end
	if messagenum < 2 then
		pendmail = pendmail + 1
		self.db.char.new, self.db.char.total = self.db.char.new + 1, self.db.char.total + 1
		if checked then self.db.char.total = GetInboxNumItems() + self.db.char.new end
		if self.db.profile.playsounds then PlaySoundFile(files.soundpath) end
		if self.db.profile.chatalerts then self:Print(L["New Mail Received (%d/%d)"], self.db.char.new, self.db.char.total) end

		self:Update()
		messagenum = messagenum + 1
	else 
		messagenum = 1 
	end
end


function FuBar_Mail:SpecialEvents_AHAlert(ahtype, item)
	if not self.db.char.ahalerts then self.db.char.ahalerts = {} end
	table.insert(self.db.char.ahalerts, {L[ahtype], item})

	self:Update()
end


function FuBar_Mail:OnTextUpdate()
--	self.hasNoText = self:IsIconShown() and not self.db.profile.showtext and not self.db.profile.showcount
	local showt = self.db.profile.textformat == L.both or self.db.profile.textformat == L.text
	local showc = self.db.profile.textformat == L.both or self.db.profile.textformat == L.number
	local hasmail = self.db.char.ahalerts or self.db.char.total > 0 or (HasNewMail() and not checked)
	local numstr = (self.db.char.total > 0) and string.format(showt and "(%u/%u)" or "%u/%u", self.db.char.new, self.db.char.total) or showt and "(0)" or "0"
	local colorstr = self.db.char.ahalerts and "|cffff0000" or hasmail and "|cff00ff00" or ""
	local txtstr = self.db.char.ahalerts and L["AH Alert!"] or hasmail and L["New Mail"] or L["No mail"]

	self:SetText(colorstr.. (showt and txtstr or "").. (showt and showc and " " or "").. (showc and numstr or ""))
	self:SetIcon(self.db.char.ahalerts and files.iconAH or hasmail and files.iconnew or files.iconnomail)
end


function FuBar_Mail:OnTooltipUpdate()
	local hasmail = self.db.char.ahalerts or self.db.char.total > 0 or (HasNewMail() and not checked)
	local colorstr = self.db.char.ahalerts and "|cffff0000" or hasmail and "|cff00ff00" or ""
	local txtstr = self.db.char.ahalerts and L["AH Alert!"] or hasmail and L["New Mail"] or L["No mail"]

	Tablet:SetTitle(colorstr..txtstr)

	local cat = Tablet:AddCategory("columns", 2)
	cat:AddLine("text", L["New"], "text2", self.db.char.new or "No data", "textR", 0, "textG", 1, "textB", 0, "text2R", 0, "text2G", 1, "text2B", 0)
	cat:AddLine("text", L["Total"], "text2", self.db.char.total)
	if self.db.char.ahalerts then
		cat = Tablet:AddCategory("text", "Auction Alerts", "isTitle", true, "justify", "CENTER")
		cat = Tablet:AddCategory("hideBlankLine", true, "columns", 2, "child_textR", 1, "child_textG", 0, "child_textB", 0, "child_text2R", 1, "child_text2G", 0, "child_text2B", 0)
		for _,val in ipairs(self.db.char.ahalerts) do cat:AddLine("text", val[1], "text2", val[2]) end
	end
end


