local Cartographer_Cleanup = Cartographer:NewModule("Cleanup", "AceConsole-2.0")
local L = AceLibrary("AceLocale-2.2"):new("Cartographer_Cleanup")

L:RegisterTranslations("enUS", function() return {
	["Cleanup"] = true,
	["Clean up duplicate notes of the same type and name"] = true,
	["Clean distance"] = true,
	["The amount of yards of which a note with the same data has to be in, before being considered a duplicate"] = true,
	["Enter the amount of yards you wish use"] = true,
	["Clean this zone"] = true,
	["Clean the notes in the current Zone."] = true,
	["Clean all zones"] = true,
	["Clean the notes in all known zones."] = true,
	["Deleting %s by %s in %s"] = true;
	["Cleaning %s for %s"] = true;
	["Deleting %s in %s on (%s,%s)"] = true;
	["Cleaned %s for %s"] = true;
} end)

L:RegisterTranslations("koKR", function() return {
	["Cleanup"] = "청소",
	["Clean up duplicate notes of the same type and name"] = "똑같은 형식의 이름 중복 노트를 정리합니다.",
	["Clean distance"] = "거리 청소",
	["The amount of yards of which a note with the same data has to be in, before being considered a duplicate"] = "중복이라고 생각되기 전에 어느 정도 상당량의 똑같은 거리 데이터가 있는 노트가 있어야 합니다.",
	["Enter the amount of yards you wish use"] = "원하는 거리 입력",
	["Clean this zone"] = "지금 지역 청소",
	["Clean the notes in the current Zone."] = "현재 지역의 노트를 청소합니다.",
	["Clean all zones"] = "모든 지역 청소",
	["Clean the notes in all known zones."] = "모든 지역의 노트를 청소합니다.",
	["Deleting %s by %s in %s"] = "삭제 %s : %s (%s)";
	["Cleaning %s for %s"] = "청소 %s : %s";
	["Deleting %s in %s on (%s,%s)"] = "삭제 %s : %s - (%s,%s)";
	["Cleaned %s for %s"] = "청소 %s : %s";
} end)

L:RegisterTranslations("zhTW", function() return {
	["Cleanup"] = "大掃除",
	["Clean up duplicate notes of the same type and name"] = "掃除 Cartographer 在地圖上的重複記號。",
	["Clean distance"] = "掃除距離",
	["The amount of yards of which a note with the same data has to be in, before being considered a duplicate"] = "重複記號最大距離",
	["Enter the amount of yards you wish use"] = "輸入重複記號最大距離",
	["Clean this zone"] = "掃除目前地區",
	["Clean the notes in the current Zone."] = "掃除目前地區的重複記號。",
	["Clean all zones"] = "掃除所有地區",
	["Clean the notes in all known zones."] = "掃除所有地區的重複記號。",
	["Deleting %s by %s in %s"] = "刪除: %s，新增者: %s，地區: %s";
	["Cleaning %s for %s"] = "掃除地區: %s，模組: %s";
	["Deleting %s in %s on (%s,%s)"] = "刪除: %s，地區: %s (%s，%s)";
	["Cleaned %s for %s"] = "已掃除地區: %s，模組: %s";
} end)

local BZ = AceLibrary("Babble-Zone-2.2")
local Tourist = AceLibrary("Tourist-2.0")

function Cartographer_Cleanup:OnInitialize()
	self.db = Cartographer:AcquireDBNamespace("Cleanup")
	Cartographer:RegisterDefaults("Cleanup", "profile", {
		yards = 10,
	})
	
	Cartographer.options.args.Cleanup = {
		name = L["Cleanup"],
		desc = L["Clean up duplicate notes of the same type and name"],
		handler = self,
		type = 'group',
		args = {
			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,				
			},
			yards = {
				name = L["Clean distance"],
				desc = L["The amount of yards of which a note with the same data has to be in, before being considered a duplicate"],
				type = "range",
				max = 100,
				min = 5,
				step = 1,
				order = 1,
				get = "GetYards",
				set = "SetYards",
				disabled = function() return not Cartographer:IsModuleActive(self) end,
			},
			zone = {
				name = L["Clean this zone"],
				desc = L["Clean the notes in the current Zone."],
				type = "execute",
				func = "DoZoneCleanup",
				order = 4,
				disabled = function() return not Cartographer:IsModuleActive(self) end,
			},
			all = {
				name = L["Clean all zones"],
				desc = L["Clean the notes in all known zones."],
				type = "execute",
				func = "DoFullCleanup",
				order = 4,
				args = {},
				disabled = function() return not Cartographer:IsModuleActive(self) end,
			},
		},
	}

	AceLibrary("AceConsole-2.0"):InjectAceOptionsTable(self, Cartographer.options.args.Cleanup)
end

function Cartographer_Cleanup:ValidateYards(yards)
	return yards:find("^[0-9]+$")
end

function Cartographer_Cleanup:GetYards()
	return self.db.profile.yards
end
function Cartographer_Cleanup:SetYards(value)
	self.db.profile.yards = tonumber(value)
end

function Cartographer_Cleanup:OnEnable()
	-- Nothing here, hrm
end

function Cartographer_Cleanup:DoFullCleanup()
	for zone in Tourist:IterateZones() do
		Cartographer_Cleanup:DoZoneCleanup(zone);
	end
end

function Cartographer_Cleanup:DoZoneCleanup(zone)
	zone = zone or Cartographer:GetCurrentLocalizedZoneName();
	for database, _ in pairs(Cartographer_Notes.externalDBs) do
		self:DoCleanup(zone, database)
	end
	-- Ugleh, but for some reason i just totally fail at iterating main db notes /Mikk
	for k,v in pairs(Cartographer_Notes.db.account.pois[zone]) do
		if(v.icon=="Skull" and v.creator=="CorpseWay") then
			self:Print(L["Deleting %s by %s in %s"]:format(v.icon, v.creator, zone));
			Cartographer_Notes.db.account.pois[zone][k] = nil;
		end
	end
	if zone==Cartographer:GetCurrentEnglishZoneName() then
	  Cartographer_Notes:RefreshMap();
	end
end

function Cartographer_Cleanup:DoCleanup(zone, database)
	--self:Print(L["Cleaning %s for %s"]:format(zone, database))
	for zone,x,y,icon,creator,data in Cartographer_Notes:IterateNearbyNotes(zone,1,1,10000,database,nil,true) do
		for _,p_x,p_y,p_icon,_,_ in Cartographer_Notes:IterateNearbyNotes(zone, x, y, self.db.profile.yards, creator, nil, true) do
			if icon == p_icon and p_x ~= x and p_y ~= y then
				self:Print(L["Deleting %s in %s on (%s,%s)"]:format(p_icon, zone, p_x, p_y))
				Cartographer_Notes:DeleteNote(zone, p_x, p_y)
				
				-- respin, because the loop has changed (Ugly, I know)
				Cartographer_Cleanup:DoCleanup(zone, database)
				return
				
			end					
		end
	end
	self:Print(L["Cleaned %s for %s"]:format(zone, database))
end