local bs = AceLibrary("Babble-Spell-2.2")
local AceAddon = AceLibrary("AceAddon-2.0")
local Tablet = AceLibrary("Tablet-2.0")

local L = AceLibrary("AceLocale-2.2"):new("Cartographer_Opening")
L:RegisterTranslations("enUS", function() return {
	["Filter"] = true,
	["Filter out treasures"] = true,
	
	["Select all"] = true,
	["Select none"] = true,
	

	["Power Crystal"] = true,
	["Blue Power Crystal"] = true,
	["Red Power Crystal"] = true,
	["Yellow Power Crystal"] = true,
	["Green Power Crystal"] = true,

	["UnGoro Dirt Pile"] = "", -- need translation
	["UnGoro Soil"] = "", -- need translation
	["Bloodpetal Sprout"] = true,
	["Blood of Heroes"] = true,

	["Night Dragon's Breath"] = true,
	["Whipper Root Tuber"] = true,
	["Windblossom Berries"] = true,
	["SongFlower"] = true,


	["Ancient Treasure"] = true,
	["Large Solid Chest"] = true,
	["Solid Chest"] = true,
	["Alliance Chest"] = true,
	["Horde Chest"] = true,
	["Chest"] = true,

} end)

L:RegisterTranslations("koKR", function() return {
	["Filter"] = "필터링",
	["Filter out treasures"] = "습득물의 종류에 따라 표시 여부를 선택합니다.",
	
	["Select all"] = "모두 선택",
	["Select none"] = "선택 해제",
	

	["Power Crystal"] = "마력의 수정",
	["Blue Power Crystal"] = "푸른 마력의 수정",
	["Red Power Crystal"] = "붉은 마력의 수정",
	["Yellow Power Crystal"] = "노란 마력의 수정",
	["Green Power Crystal"] = "녹색 마력의 수정",

	["UnGoro Dirt Pile"] = "운고로 흙더미",
	["UnGoro Soil"] = "운고로 토양",
	["Bloodpetal Sprout"] = "붉은꽃잎 씨앗",
	["Blood of Heroes"] = "영웅의 피",

	["Night Dragon's Breath"] = "어둠용의 숨결",
	["Whipper Root Tuber"] = "채찍뿌리 줄기",
	["Windblossom Berries"] = "바람꽃 열매",
	["SongFlower"] = "노래꽃",


	["Ancient Treasure"] = "낡은 궤짝",
--	["Large Solid Chest"] = true,
	["Solid Chest"] = "단단한 궤짝",
	["Alliance Chest"] = "얼라이언스 보금품 상자",
	["Horde Chest"] = "호드 보급품 상자",
	["Chest"] = "궤짝",

} end)

L:RegisterTranslations("zhTW", function() return {
	["Filter"] = "篩檢",
	["Filter out treasures"] = "篩檢寶物",
	
	["Select all"] = "全部選擇",
	["Select none"] = "全部取消",
	

	["Power Crystal"] = "能量水晶",
	["Blue Power Crystal"] = "藍色能量水晶",
	["Red Power Crystal"] = "紅色能量水晶",
	["Yellow Power Crystal"] = "黃色能量水晶",
	["Green Power Crystal"] = "綠色能量水晶",

	["UnGoro Dirt Pile"] = "安戈洛土堆", -- need translation
	["UnGoro Soil"] = "安戈洛的泥土", -- need translation
	["Bloodpetal Sprout"] = "血瓣花苗",
	["Blood of Heroes"] = "英雄之血",

	["Night Dragon's Breath"] = "夜龍之息",
	["Whipper Root Tuber"] = "鞭根塊莖",
	["Windblossom Berries"] = "風花果",
	["SongFlower"] = "輕歌花",


	["Ancient Treasure"] = "古代寶藏",
	["Large Solid Chest"] = "堅固的大箱子",
	["Solid Chest"] = "堅固的箱子",
	["Alliance Chest"] = "聯盟寶箱",
	["Horde Chest"] = "部落寶箱",
	["Chest"] = "箱子",

} end)

L:RegisterTranslations("esES", function() return {
	["Filter"] = "Filtro",
	["Filter out treasures"] = "Filtra tesoros",
	
	["Select all"] = "Seleccionar todo",
	["Select none"] = "No seleccionar nada",
	

	["Power Crystal"] = "Cristales de poder",
	["Blue Power Crystal"] = "Cristal de Poder Azul",
	["Red Power Crystal"] = "Cristal de poder Rojo",
	["Yellow Power Crystal"] = "Cristal de poder Amarillo",
	["Green Power Crystal"] = "Cristal de poder Verde",

--	["UnGoro Dirt Pile"] = true,
	["UnGoro Soil"] = "Tierra de Un'Goro",
	["Bloodpetal Sprout"] = "Brote p�talo de sangre",
	["Blood of Heroes"] = "Sangre de h�roes",

	["Night Dragon's Breath"] = "Aliento de Drag�n nocturno",
	["Whipper Root Tuber"] = "Tub�rculo de blancoria",
	["Windblossom Berries"] = "Frutos de la flor del viento",
--	["SongFlower"] = true,


--	["Ancient Treasure"] = true,
--	["Large Solid Chest"] = true,
--	["Solid Chest"] = true,
--	["Alliance Chest"] = true,
--	["Horde Chest"] = true,
--	["Chest"] = true,

} end)

local mod = Cartographer:NewModule(bs["Opening"], "AceConsole-2.0", "AceEvent-2.0")

mod.icon = {
	["Power Crystal"] = {
		text = L["Power Crystal"],
		path = "Interface\\Icons\\INV_Misc_Gem_Topaz_02",
		width = 12,
		height = 12
	},
	["UnGoro Soil"] = {
		text = L["UnGoro Soil"],
		path = "Interface\\Icons\\INV_Misc_Dust_02",
		width = 12,
		height = 12
	},
	["Bloodpetal Sprout"] = {
		text = L["Bloodpetal Sprout"],
		path = "Interface\\Icons\\INV_Misc_Food_45",
		width = 12,
		height = 12
	},
	["Blood of Heroes"] = {
		text = L["Blood of Heroes"],
		path = "Interface\\Icons\\INV_Potion_33",
		width = 12,
		height = 12
	},
	["Night Dragon's Breath"] = {
		text = L["Night Dragon's Breath"],
		path = "Interface\\Icons\\INV_Misc_Food_45",
		width = 12,
		height = 12
	},
	["Whipper Root Tuber"] = {
		text = L["Whipper Root Tuber"],
		path = "Interface\\Icons\\INV_Misc_Food_55",
		width = 12,
		height = 12
	},
	["Windblossom Berries"] = {
		text = L["Windblossom Berries"],
		path = "Interface\\Icons\\INV_Misc_Food_58",
		width = 12,
		height = 12
	},
	["SongFlower"] = {
		text = L["SongFlower"],
		path = "Interface\\Icons\\Spell_Holy_MindVision",
		width = 12,
		height = 12
	},
	["Chest"] = {
		text = L["Chest"],
		path = "Interface\\Icons\\INV_Box_03",
		width = 12,
		height = 12
	},
}

function mod:OnInitialize()
	self.db = Cartographer:AcquireDBNamespace("Opening")
	Cartographer:RegisterDefaults("Opening", "profile", {
		filter = {
			['*'] = true,
		}
	})

	local aceopts = {}
	aceopts.toggle = {
		name = AceLibrary("AceLocale-2.2"):new("Cartographer")["Enabled"],
		desc = AceLibrary("AceLocale-2.2"):new("Cartographer")["Suspend/resume this module."],
		type  = 'toggle',
		order = -1,
		get   = function() return Cartographer:IsModuleActive(self) end,
		set   = function() Cartographer:ToggleModuleActive(self) end,
	}

	aceopts.filter = {
		name = L["Filter"],
		desc = L["Filter out treasures"],
		type = 'group',
		args = {
			all = {
				name = L["Select all"],
				desc = L["Select all"],
				type = 'execute',
				func = function()
					for k in pairs(self.icon) do
						self:ToggleShowingTreasure(k, true)
					end
				end,
				order = 1,
			},
			none = {
				name = L["Select none"],
				desc = L["Select none"],
				type = 'execute',
				func = function()
					for k in pairs(self.icon) do
						self:ToggleShowingTreasure(k, false)
					end
				end,
				order = 2,
			},
			blank = {
				type = 'header',
				order = 3,
			}
		}
	}
	for k,v in pairs(self.icon) do
		local k = k
		aceopts.filter.args[k] = {
			name = v.text,
			desc = v.text,
			type = 'toggle',
			get = function()
				return self:IsShowingTreasure(k)
			end,
			set = function(value)
				return self:ToggleShowingTreasure(k, value)
			end,
		}
	end

	Cartographer.options.args[bs["Opening"]] = {
		name = bs["Opening"],
		desc = self.notes,
		type = 'group',
		args = aceopts,
		handler = self,
	}
	AceLibrary("AceConsole-2.0"):InjectAceOptionsTable(self, Cartographer.options.args[bs["Opening"]])

	if not Cartographer_OpeningDB then
		Cartographer_OpeningDB = {}
	end
end

function mod:OnEnable()
	if Cartographer_Notes then
		if not self.iconsregistered then
			for k,v in pairs(self.icon) do
				Cartographer_Notes:RegisterIcon(k, v)
			end
			self.iconsregistered = true
		end

		Cartographer_Notes:RegisterNotesDatabase('Opening', Cartographer_OpeningDB, self)
	else
		Cartographer:ToggleModuleActive(self, false)
	end

	self:RegisterEvent("UI_ERROR_MESSAGE")

--	self:RegisterEvent("CHAT_MSG_SPELL_SELF_BUFF")
	self:RegisterEvent("UNIT_SPELLCAST_START")

end

function mod:OnDisable()
	self:UnregisterAllEvents()

	if Cartographer_Notes then
		Cartographer_Notes:UnregisterNotesDatabase('Opening')
	end
end

function mod:SetNote(what)
	local x, y = GetPlayerMapPosition("player")
	if x == 0 and y == 0 then return end
	local zone = GetRealZoneText()
	for zone, x_p, y_p, icon, creator, data in Cartographer_Notes:IterateNearbyNotes(zone, x, y, 5, "Opening", nil, true) do
		if icon == what then
			Cartographer_Notes:DeleteNote(zone, x_p, y_p)
		end
	end
	Cartographer_Notes:SetNote(zone, x, y, what, "Opening")
end

function mod:OnNoteTooltipRequest(zone, id, treasure, minimap)
	Tablet:SetTitle(L[treasure])
	Tablet:SetTitleColor(0, 0.8, 0)
	
	if Cartographer_Notes:IsShowingCreator() and not minimap then
		Tablet:AddCategory(
			'columns', 2,
			'hideBlankLine', true
		):AddLine(
			'text', AceLibrary("AceLocale-2.2"):new("Cartographer-Notes")["Created by"],
			'text2', bs["Opening"]
		)
	end
end

local t = {
	[L["Blue Power Crystal"]] = "Power Crystal",
	[L["Red Power Crystal"]] = "Power Crystal",
	[L["Yellow Power Crystal"]] = "Power Crystal",
	[L["Green Power Crystal"]] = "Power Crystal",
	[L["UnGoro Dirt Pile"]] = "UnGoro Soil",
	[L["Bloodpetal Sprout"]] = "Bloodpetal Sprout",
	[L["Blood of Heroes"]] = "Blood of Heroes",

	[L["Night Dragon's Breath"]] = "Night Dragon's Breath",
	[L["Whipper Root Tuber"]] = "Whipper Root Tuber",
	[L["Windblossom Berries"]] = "Windblossom Berries",
	[L["SongFlower"]] = "SongFlower",

	[L["Ancient Treasure"]] = "Chest",
	[L["Large Solid Chest"]] = "Chest",
	[L["Solid Chest"]] = "Chest",
	[L["Alliance Chest"]] = "Chest",
	[L["Horde Chest"]] = "Chest",
}

function mod:RegisterTreasure(what)
	if what and what:len() > 0 then
		what = what:gsub("^(.-) %(%d+%)$", "%1")
		local treasure = t[what]
		if treasure then
			self:SetNote(treasure)
		end
	end
end

local perform_string = '^' .. (SIMPLEPERFORMSELFOTHER:format(bs["Opening"], "%s"):gsub("([%(%)%.%*%+%-%[%]%?%^%$%%])", "%%%1"):gsub("%%%%s", "(.+)")) .. '$'
function mod:UNIT_SPELLCAST_START(a1)

	if ( a1 ~= "player" ) then return end
	local _, _, text, _, _, _ = UnitCastingInfo("player")
	if text == bs["Opening"] then
--		local what = GameTooltipTextLeft1:GetText()
		self:RegisterTreasure(GameTooltipTextLeft1:GetText())
	end

--[[	local what = msg:match(perform_string)
	if what then
		self:RegisterTreasure(what)
	end]]
end

function mod:UI_ERROR_MESSAGE(msg)
	if msg:find(SPELL_FAILED_NOT_MOUNTED) or msg:find(ERR_NOT_IN_COMBAT) then
		self:RegisterTreasure(GameTooltipTextLeft1:GetText())
	end
end

function mod:IsNoteHidden(zone, id, treasure)
	return not self.db.profile.filter[treasure]
end

function mod:IsShowingTreasure(treasure)
	return self.db.profile.filter[treasure]
end

function mod:ToggleShowingTreasure(treasure, value)
	if value == nil then
		value = not self.db.profile.filter[treasure]
	end
	self.db.profile.filter[treasure] = value

	Cartographer_Notes:RefreshMap()
end
