local AceAddon = AceLibrary("AceAddon-2.0")
local Tablet = AceLibrary("Tablet-2.0")
local Tooltip = AceLibrary("Gratuity-2.0")
local BV = AceLibrary("Babble-Vendor-2.2")

local L = AceLibrary("AceLocale-2.2"):new("Cartographer_Vendors")
L:RegisterTranslations("enUS", function() return {
	["Filter"] = true,
	["Filter out vendors"] = true,
	
    ["Vendors"] = true,
    ["Module description"] = "Vendor Mapnotes for Cartographer",
  
	["Select all"] = true,
	["Select none"] = true,

    ["Icon alpha"] = true,
	["Alpha transparency of the icon"] = true,
	["Icon size"] = true,
	["Size of the icons on the map"] = true,    
    ["Show minimap icons"] = true,
    ["Show vendor icons on the minimap"] = true,
    ["Show minimap tracking icons"] = true,
    ["Show vendor tracking icons on the minimap"] = true,
    
    ["Import"] = true,
    ["Import vendors"] = true,
    ["Rebuild"] = true,
    ["Rebuild vendors"] = true,

    -- Filters
    ["Vendor"] = true,
--    ["Armorer"] = true,
    ["Merchants"] = true,
    ["Food and Drink"] = true,
    ["Armor"] = true,
    ["Weapons"] = true,
--    ["Goods"] = true,
    ["Miscellaneous"] = true,
    ["Trainers"] = true,
    ["Faction"] = true,
    ["Tradeskill"] = true,
    ["Class"] = true,
  
} end)

L:RegisterTranslations("koKR", function() return {
	["Filter"] = "항목 분류",
	["Filter out vendors"] = "상인 정보를 항목에 따라 분류해서 표시합니다.",

    ["Vendors"] = "상인",
    ["Module description"] = "맵노트에 상인을 표시합니다.",
	
	["Select all"] = "모두 선택",
	["Select none"] = "선택 없음",

    ["Icon alpha"] = "아이콘 투명도",
	["Alpha transparency of the icon"] = "아이콘의 투명도를 조절합니다.",
	["Icon size"] = "아이콘 크기",
	["Size of the icons on the map"] = "아이콘의 크기를 조절합니다.",
    ["Show minimap icons"] = "미니맵 아이콘 보기",
    ["Show vendor icons on the minimap"] = "미니맵에 상인 아이콘을 표시합니다.",
    ["Show minimap tracking icons"] = "미니맵에 추적 아이콘 보기",
    ["Show vendor tracking icons on the minimap"] = "미니맵에 상인 추적 아이콘을 표시합니다.",
    
    ["Import"] = "외부 데이터 입력",
    ["Import vendors"] = "상인 정보를 입력합니다.",
    ["Rebuild"] = "재배치",
    ["Rebuild vendors"] = "상인 정보를 재배치 합니다.",
    
    -- Filters
    ["Vendor"] = "상인",
--    ["Armorer"] = "방어구",
    ["Merchants"] = "상인",
    ["Food and Drink"] = "음료 및 요리",
    ["Armor"] = "방어구",
    ["Weapons"] = "무기",
--    ["Goods"] = "일용품",
    ["Miscellaneous"] = "기타",
    ["Trainers"] = "기술자",
    ["Faction"] = "평판",
    ["Tradeskill"] = "전문기술",
    ["Class"] = "직업",
} end)

L:RegisterTranslations("deDE", function() return {
	["Filter"] = "Filter",
	["Filter out vendors"] = "H\195\164ndler filtern",
	
    ["Vendors"] = "H\195\164ndler",
    ["Module description"] = "H\195\164ndler-Kartennotizen f\195\188r Cartographer",

    ["Select all"] = "Alles ausw\195\164hlen",
    ["Select none"] = "Nichts ausw\195\164hlen",

    ["Icon alpha"] = "Transparenz",
    ["Alpha transparency of the icon"] = "Transparenz der Symbole.",
    ["Icon size"] = "Symbolgr\195\182\195\159e",
    ["Size of the icons on the map"] = "Gr\195\182\195\159e der Symbole auf der Karte.",
    ["Show minimap icons"] = "Minimap-Symbole anzeigen",
    ["Show vendor icons on the minimap"] = "H\195\164ndlersymbole auf der Minimap anzeigen.",
    ["Show minimap tracking icons"] = "Ortungssymbole anzeigen",
    ["Show vendor tracking icons on the minimap"] = "H\195\164ndler-Symbole auf der Minimap schalten bei Annäherung auf Ortungskreise um.",

    ["Import"] = "Import",
    ["Import vendors"] = "Importiere H\195\164ndlerdaten",
    ["Rebuild"] = "Rekonstruktion",
    ["Rebuild vendors"] = "Rekonstruktion der H\195\164ndlerdaten.",
    ["Vendor"] = "H\195\164ndler",
    
    -- Filters
--    ["Vendor"] = "Verkäufer",
    ["Armorer"] = "Rüstungsschmied",
--    ["Merchants"] = "Händler",
    ["Food and Drink"] = "Essen und Getränke",
    ["Armor"] = "Rüstungen",
    ["Weapons"] = "Waffen",
--    ["Goods"] = "Waren",
    ["Miscellaneous"] = "Gemischtwaren",
    ["Trainers"] = "Lehrer",
    ["Faction"] = "Faction",

} end)

L:RegisterTranslations("zhTW", function() return {
	["Filter"] = "篩檢",
	["Filter out vendors"] = "篩檢商人",
	
    ["Vendors"] = "商人",
    ["Module description"] = "Cartographer 商人地圖註記",

    ["Select all"] = "全部選擇",
    ["Select none"] = "全部取消",
    
    ["Icon alpha"] = true,
	["Alpha transparency of the icon"] = true,
	["Icon size"] = true,
	["Size of the icons on the map"] = true,    
    ["Show minimap icons"] = true,
    ["Show vendor icons on the minimap"] = true,
    ["Show minimap tracking icons"] = true,
    ["Show vendor tracking icons on the minimap"] = true,
    
    ["Import"] = true,
    ["Import vendors"] = true,
    ["Rebuild"] = true,
    ["Rebuild vendors"] = true,    

--    ["Vendor"] = "商人",
} end)

L:RegisterTranslations("esES", function() return {
	["Filter"] = "Filtrar",
	["Filter out vendors"] = "Filtra vendedores",
	
    ["Vendors"] = "Vendedores",
    ["Module description"] = "Notas de mapa de vendedores para Cartographer",

    ["Select all"] = "Seleccionar todo",
    ["Select none"] = "No seleccionar nada",

    ["Icon alpha"] = "Transparencia de icono",
    ["Alpha transparency of the icon"] = "Transparencia del icono",
    ["Icon size"] = "Tama\195\177o del icono",
    ["Size of the icons on the map"] = "Tama\195\177o de los iconos en el mapa",
    ["Show minimap icons"] = "Mostrar iconos en minimapa",
    ["Show vendor icons on the minimap"] = "Muestra los iconos de vendedores en el minimapa",
    ["Show minimap tracking icons"] = "Mostrar iconos de seguimiento en minimapa",
    ["Show vendor tracking icons on the minimap"] = "Muestra los iconos de seguimiento de vendedores en el minimapa",
    
    ["Import"] = "Importar",
    ["Import vendors"] = "Importa vendedores",
    ["Rebuild"] = "Reconstruir",
    ["Rebuild vendors"] = "Reconstruye vendedores",
    
--    ["Vendor"] = "Vendedor",

    -- Filters
--    ["Vendor"] = "Vendedor",
--    ["Armorer"] = "Armero",
--    ["Merchants"] = "Mercaderes",
    ["Food and Drink"] = "Comida y Bebida",
    ["Armor"] = "Armadura",
    ["Weapons"] = "Armas",
--    ["Goods"] = "Pertrechos",
    ["Miscellaneous"] = "Miscel\195\161neo",
    ["Trainers"] = "Instructores",
    ["Faction"] = "Faction",
} end)

Cartographer_Vendors = Cartographer:NewModule("Vendors", "AceConsole-2.0", "AceEvent-2.0", "AceDB-2.0")
Cartographer_Vendors.revision = tonumber(string.sub("$Revision: 28867 $", 12, -3))
Cartographer_Vendors.version = "r" .. Cartographer_Vendors.revision
Cartographer_Vendors.date = string.sub("$Date: 2007-02-24 05:37:39 -0500 (Sat, 24 Feb 2007) $", 8, 17)
Cartographer_Vendors:RegisterDB("Cartographer_VendorsDB")

Cartographer_Vendors.filters = {
    ["Armor"] = L["Armor"],
    ["Food and Drink"] = L["Food and Drink"],
--    ["Goods"] = L["Goods"],
--    ["Merchants"] = L["Merchants"],
    ["Miscellaneous"] = L["Miscellaneous"],
    ["Trainers"] = L["Trainers"],
    ["Weapons"] = L["Weapons"],
    ["Faction"] = L["Faction"],
    ["Tradeskill"] = L["Tradeskill"],
    ["Class"] = L["Class"],
}

Cartographer_Vendors.lookups = {
    ["filters"] = {
        ["가방 상인"] = "Miscellaneous",
        ["가죽 및 사슬 방어구 상인"] = "Armor",
        ["가죽 방어구 상인"] = "Armor",
        ["가죽세공용품 상인"] = "Tradeskill",
        ["갑옷 및 대장용품 상인"] = "Armor",
        ["갑옷 및 방패 상인"] = "Armor",
        ["검 상인"] = "Weapons",
        ["검과 단검 상인"] = "Weapons",
        ["고급 둔기제작자"] = "Weapons",
        ["고급 방어구 제작자"] = "Armor",
        ["고기 상인"] = "Food and Drink",
        ["과일 상인"] = "Food and Drink",
        ["기계타조 상인"] = "Miscellaneous",
        ["기술 및 채광용품 상인"] = "Tradeskill",
        ["기술용품 상인"] = "Tradeskill",
--        ["길드 사무관"] = "Miscellaneous",
        ["길드 휘장 상인"] = "Miscellaneous",
        ["낚시용품 상인"] = "Tradeskill",
        ["낚시 용품 상인"] = "Tradeskill",
	["낚시꾼"] = "Tradeskill",
        ["다크문 유랑단 음료 상인"] = "Food and Drink",
        ["다크문 유랑단 음식 상인"] = "Food and Drink",
        ["단검 상인"] = "Weapons",
        ["대장 및 채광용품 상인"] = "Tradeskill",
        ["대장용품 상인"] = "Tradeskill",
        ["도검류 상인"] = "Weapons",
        ["도끼 상인"] = "Weapons",
        ["독극물 재료 상인"] = "Class",
        ["두루마리 및 물약 상인"] = "Miscellaneous",
        ["둔기 및 지팡이 상인"] = "Weapons",
        ["땅다람쥐 상인"] = "Miscellaneous",
        ["로브 상인"] = "Armor",
        ["마그하르 병참장교"] = "Faction",
        ["마법 재료 상인"] = "Class",
        ["마법봉 상인"] = "Weapons",
        ["마법부여용품 상인"] = "Tradeskill",
        ["마법용품 상인"] = "Tradeskill",
        ["마법재료 상인"] = "Class",
        ["무기 상인"] = "Weapons",
        ["무기제작자"] = "Weapons",
        ["무역연합 병참장교"] = "Faction",
        ["바퀴벌레 상인"] = "Miscellaneous",
        ["방어구 및 무기 상인"] = "Armor",
        ["방어구 상인"] = "Armor",
        ["방어구 제작가"] = "Armor",
        ["방패 상인"] = "Armor",
        ["버섯 상인"] = "Food and Drink",
        ["버클러 상인"] = "Armor",
        ["병참 장교"] = "Faction",
        ["보석 상인"] = "Miscellaneous",
        ["보석세공용품 상인"] = "Tradeskill",
        ["비전투장비 병참장교"] = "Faction",
        ["빵 상인"] = "Food and Drink",
        ["사슬 방어구 상인"] = "Armor",
        ["생선 상인"] = "Food and Drink",
        ["서리늑대 병참장교"] = "Faction",
        ["세나리온 원정대 병참장교"] = "Faction",
        ["스랄마 병참장교"] = "Faction",
        ["스톰파이크 병참장교"] = "Faction",
        ["스포어가르 보급원"] = "Faction",
        ["시간의 수호자 병참장교"] = "Faction",
        ["식료품 상인"] = "Food and Drink",
        ["아라소르 연맹 병참장교"] = "Faction",
        ["아이스크림 상인"] = "Food and Drink",
        ["양손 무기 상인"] = "Weapons",
        ["언데드 말 조련사"] = "Miscellaneous",
        ["얼라이언스 천 방어구 병참장교"] = "Faction",
        ["여관주인"] = "Miscellaneous",
        ["연금술용품 상인"] = "Tradeskill",
        ["와인 및 술 상인"] = "Food and Drink",
        ["와인 상인"] = "Miscellaneous",
        ["요리 재료 상인"] = "Tradeskill",
        ["은빛날개 병참장교"] = "Faction",
        ["음료 상인"] = "Food and Drink",
        ["음식 상인"] = "Food and Drink",
        ["일용품 상인"] = "Miscellaneous",
        ["재봉용품 상인"] = "Tradeskill",
        ["전문 무기제작자"] = "Weapons",
        ["전문 요리사 및 요리 용품 상인"] = "Trainers",
        ["전쟁노래 병참장교"] = "Faction",
        ["전투 멜빵 상인"] = "Armor",
        ["점술가 길드 병참장교"] = "Faction",
        ["지팡이 및 둔기 상인"] = "Weapons",
        ["지팡이 상인"] = "Weapons",
        ["직업용품 상인"] = "Tradeskill",
        ["진귀한 마법 재료 상인"] = "Class",
        ["채광용품 상인"] = "Tradeskill",
        ["천 및 가죽 방어구 상인"] = "Armor",
        ["천 방어구 상인"] = "Armor",
        ["철퇴제작자"] = "Weapons",
        ["총기류 상인"] = "Weapons",
        ["치즈 상인"] = "Food and Drink",
        ["쿠레나이 병참장교"] = "Faction",
        ["탄약 상인"] = "Weapons",
        ["투기장 사무관"] = "Faction",
        ["투자개발회사 무기 외판원"] = "Miscellaneous",
        ["투척 무기 상인"] = "Weapons",
        ["특수 무기제작자"] = "Weapons",
        ["특수 재봉용품 상인"] = "Tradeskill",
        ["특제 의상 상인"] = "Miscellaneous",
        ["파멸단 병참장교"] = "Faction",
        ["폭죽 상인"] = "Miscellaneous",
        ["푸줏간 주인"] = "Food and Drink",
        ["해적 애완동물 상인"] = "Miscellaneous",
        ["호드 천 방어구 병참장교"] = "Faction",
        ["화살 상인"] = "Weapons",
        ["활 및 총기류 상인"] = "Weapons",
        ["활 상인"] = "Weapons",
	["버섯 상인"] = "Food and Drink",
	["파이 상인"] = "Food and Drink",
	["빵 행상인"] = "Food and Drink",
    },
}

Cartographer_Vendors.icons = {
	["Vendor"] = {
		text = L["Vendor"],
		path = "Interface\\AddOns\\Cartographer_Vendors\\Artwork\\INV_Misc_Gem_BloodGem_02",
		width = 12,
		height = 12
	},
}

Cartographer_Vendors.vendors = {}

Cartographer_Vendors.noteDefaults = {
	titleCol = Cartographer_Notes.getColorID(0, 0.8, 0)
}

Cartographer_Vendors.noteLocaleHandler = BV

function Cartographer_Vendors:OnInitialize()
	self:RegisterDefaults("profile", {
		filters = {
			['*'] = true,
		},
        iconAlpha = 1,
		iconScale = 1,
        minimapIcons = true,
        minimapTracking = true,
        noteRadius = 15,        
	})
    
    self:RegisterDefaults("faction", {
        vendors = {
            ['*'] = {
                ['*'] = {},
            },
        },
    })

	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.alpha = {
		name = L["Icon alpha"],
		desc = L["Alpha transparency of the icon"],
		type = 'range',
		min = 0.1,
		max = 1,
		step = 0.01,
		bigStep = 0.05,
		isPercent = true,
        set = function(v)
            self.db.profile.iconAlpha = v
            Cartographer_Notes:RefreshMap()
        end,
        get = function() return self.db.profile.iconAlpha end,
		order = 1
	}
	aceopts.scale = {
		name = L["Icon size"],
		desc = L["Size of the icons on the map"],
		type = 'range',
		min = 0.5,
		max = 2,
		step = 0.01,
		bigStep = 0.05,
		isPercent = true,
        set = function(v) 
            self.db.profile.iconScale = v
            Cartographer_Notes:RefreshMap()
        end,
        get = function() return self.db.profile.iconScale end,
		order = 2
	}    
    aceopts.minimapicons = {
		name = L["Show minimap icons"],
		desc = L["Show vendor icons on the minimap"],
		type = 'toggle',
        set = function()
            self.db.profile.minimapIcons = not self.db.profile.minimapIcons
            Cartographer_Notes:RefreshMap()
        end,
        get = function() return self.db.profile.minimapIcons end,
		order = 3,
	}
    
    aceopts.minimaptracking = {
        name = L["Show minimap tracking icons"],
        desc = L["Show vendor tracking icons on the minimap"],
        type = 'toggle',
        set = function() 
            self.db.profile.minimapTracking = not self.db.profile.minimapTracking
            Cartographer_Notes:RefreshMap()
        end,
        get = function() return self.db.profile.minimapTracking end,
        order = 4,
        hidden = function() return not self.db.profile.minimapIcons end,
    }
    
	aceopts.filter = {
		name = L["Filter"],
		desc = L["Filter out vendors"],
		type = 'group',
		args = {
			all = {
				name = L["Select all"],
				desc = L["Select all"],
				type = 'execute',
				func = function()
					for k in pairs(self.filters) do
						self:ToggleShowingVendors(k, true)
					end
				end,
				order = 1,
			},
			none = {
				name = L["Select none"],
				desc = L["Select none"],
				type = 'execute',
				func = function()
					for k in pairs(self.filters) do
						self:ToggleShowingVendors(k, false)
					end
				end,
				order = 2,
			},
			blank = {
				type = 'header',
				order = 3,
			}
		},
        order = 5,
        -- hidden = true,
	}

    aceopts.rebuild = {
        name = L["Rebuild"],
        desc = L["Rebuild vendors"],
        type = 'execute',
        func = "RebuildVendors",
        order = 6,
    }

   	Cartographer.options.args.Vendors = {
		name = L["Vendors"],
		desc = L["Module description"],
		type = 'group',
		args = aceopts,
		handler = self,
	}
	-- AceLibrary("AceConsole-2.0"):InjectAceOptionsTable(self, Cartographer.options.args.Vendors)

	for k,v in pairs(self.filters) do
		local k = k
		aceopts.filter.args[k] = {
			name = v,
			desc = v,
			type = 'toggle',
			get = function()
				return self:IsShowingVendors(k)
			end,
			set = function(value)
				return self:ToggleShowingVendors(k, value)
			end,
		}
	end
    
    if (not self.db.faction.notes) then self.db.faction.notes = {} end
    
    local oldDB = Cartographer:AcquireDBNamespace("Vendors")
    if (oldDB.faction.notes) then
        for k, v in pairs(oldDB.faction.notes) do
            if (k ~= "version") and (v ~= nil) then
                if (not self.db.faction.notes[k]) then self.db.faction.notes[k] = {} end
                for vk, vv in pairs(v) do
                    if (vv ~= nil) then
                        if (not self.db.faction.notes[k][vk]) then
                            -- self.db.faction.notes[k][vk] = {}
                            self.db.faction.notes[k][vk] = vv
                        end
                    end
                end
            end
        end
    end
    oldDB = nil    
   
end

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

		Cartographer_Notes:RegisterNotesDatabase('Vendors', self.db.faction.notes, self)
	else
		Cartographer:ToggleModuleActive(self, false)
	end

    self:RegisterEvent("MERCHANT_SHOW", function() self:RegisterVendor(UnitName("NPC")) end, 2)
end

function Cartographer_Vendors:OnDisable()
	self:UnregisterAllEvents()

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

function Cartographer_Vendors:SetNote(vendor)
    if (type(vendor) == "string") then vendor = {["name"] = vendor} end
    if (type(vendor) ~= "table") then return end
    
    if (not vendor.x) or (not vendor.y) then vendor.x, vendor.y = GetPlayerMapPosition("player") end
    if (vendor.x == 0) and (vendor.y == 0) then return end
    
    if (not vendor.zone) then vendor.zone = GetRealZoneText() end
    
    local note = {}
    note.title = vendor.name
    note.icon = "Vendor"
    note.info = "Vendor"

    if (vendor.type) then
        if (self.filters[self.lookups.filters[vendor.type]] and self.icons[vendor.type]) then note.icon = vendor.type end
        note.info = vendor.type
    end
    
    for zone, x_p, y_p, icon, creator, data in Cartographer_Notes:IterateNearbyNotes(vendor.zone, vendor.x, vendor.y, (self.db.profile.noteRadius or 15), "Vendors", nil, true) do
		if data.title == note.title then
			Cartographer_Notes:DeleteNote(zone, x_p, y_p)
		end
	end
	Cartographer_Notes:SetNote(vendor.zone, vendor.x, vendor.y, note.icon, "Vendors", note)
end

function Cartographer_Vendors:RegisterVendor(vendor)
    if (not vendor) then return end
    if (type(vendor) ~= "string") then return end
    
    local zone = GetRealZoneText()
    local x,y = GetPlayerMapPosition("player")
	
	local entry = self.db.faction.vendors[zone][vendor]
    if (not entry.name) then entry.name = vendor end
    if (not entry.zone) then entry.zone = zone end
    if (not entry.x) then entry.x = x end
    if (not entry.y) then entry.y = y end
    if (not entry.type) then
        Tooltip:SetUnit("npc")
        local result = Tooltip:GetLine(2)
        if (result) then entry.type = result end
    end
    if (not entry.faction) then entry.faction = UnitFactionGroup("player") end
    self.db.faction.vendors[zone][vendor] = entry

	-- DEFAULT_CHAT_FRAME:AddMessage(string.format("\nname: %s (%s)\nzone: %s (%s,%s)", entry.name, entry.type, entry.zone, entry.x, entry.y))
    self:SetNote(entry)
end

function Cartographer_Vendors:IsNoteHidden(zone, id, vendor)
	if type(vendor) == "table" then
		return not self.db.profile.filters[self.lookups.filters[vendor.info]]
    else
		return not self.db.profile.filters[self.lookups.filters[vendor]]
	end
end

function Cartographer_Vendors:IsShowingVendors(vendortype)
	return self.db.profile.filters[vendortype]
end

function Cartographer_Vendors:ToggleShowingVendors(vendortype, value)
	if value == nil then
		value = not self.db.profile.filters[vendortype]
	end
	self.db.profile.filters[vendortype] = value

	Cartographer_Notes:RefreshMap()
end

function Cartographer_Vendors:IsTracking(zone,id,data)
    return self.db.profile.minimapTracking
end

function Cartographer_Vendors:IsMiniNoteHidden(zone,id,data)
	return not self.db.profile.minimapIcons
end

function Cartographer_Vendors:GetNoteTransparency(zone,id,data)
	return self.db.profile.iconAlpha
end

function Cartographer_Vendors:GetNoteScaling(zone,id,data)
	return self.db.profile.iconScale
end

function Cartographer_Vendors:RebuildVendors()
    local result = self.db.faction.vendors
    
    if (self.module_import) then
        for k,v in pairs(self:ImportVendors()) do
            if (v ~= nil) then
                if (not result[k]) then result[k] = {} end
                for vk,vv in pairs(v) do
                    if (vv ~= nil) then
                        result[k][vk] = vv
                    end
                end
            end
        end
    end
            
    if (result) then
        DEFAULT_CHAT_FRAME:AddMessage("Cartographer Vendor: Start rebuild.")
        -- for k, v in pairs(self.db.faction.vendors) do
        for k,v in pairs(result) do
            if (v ~= nil) then
                for kv, vv in pairs(v) do
                    if (vv ~= nil) then
                        local entry = vv
                        if (not entry.name) then entry.name = kv end
                        entry.zone = k
                        
                        if (entry.x ~= 0) and (entry.y ~= 0) then
                            local note = {}
                            note.title = entry.name
                            note.icon = "Vendor"
                            note.info = "Vendor"
                            
                            if (entry.type) then
                                if (self.filters[self.lookups.filters[entry.type]] and self.icons[entry.type]) then note.icon = entry.type end
                                note.info = entry.type
                            end
                            
                            for zone, x_p, y_p, icon, creator, data in Cartographer_Notes:IterateNearbyNotes(entry.zone, entry.x, entry.y, (self.db.profile.noteRadius or 15), "Vendors", nil, true) do

                                if data.title == note.title then
                                    Cartographer_Notes:DeleteNote(zone, x_p, y_p)
                                end
                            end
                            
                            -- DEFAULT_CHAT_FRAME:AddMessage(string.format("Cartographer Vendor: Rebuilding note ==> %s in %s (%s,%s)", entry.name, entry.zone, entry.x, entry.y))
                            -- DEFAULT_CHAT_FRAME:AddMessage(string.format("Cartographer Vendor: Rebuilding note ==> %s in %s (%s,%s)", entry.name, entry.zone, entry.x * 100, entry.y * 100))
                            Cartographer_Notes:SetNote(entry.zone, entry.x, entry.y, note.icon, "Vendors", note)                            
                        end
                    end
                end
            end
        end
        self.db.faction.vendors = result
        DEFAULT_CHAT_FRAME:AddMessage("Cartographer Vendor: Rebuild complete.")
    end
end