Cartographer_Import = AceLibrary("AceAddon-2.0"):new("AceConsole-2.0", "AceEvent-2.0")

local L = AceLibrary("AceLocale-2.2"):new("Cartographer_Import")

L:RegisterTranslations("enUS", function() return {
	["Added %s %s to %s at %.2f, %.2f from %s"] = true,
	
	["Mineral"] = true,
	["Herb"] = true,
	["Treasure"] = true,
	["Gatherer"] = true,
	["Fishing"] = true,
} end)

L:RegisterTranslations("koKR", function() return {
	["Added %s %s to %s at %.2f, %.2f from %s"] = "%s|1을;를; %s에 추가(지역: %s(%s, %s)), 애드온: %s",

	["Mineral"] = "광물",
	["Herb"] = "약초",
	["Treasure"] = "보물",
	["Gatherer"] = "게더러",
	["Fishing"] = "낚시", 
} end)

L:RegisterTranslations("zhTW", function() return {
	["Added %s %s to %s at %.2f, %.2f from %s"] = "加入 %s %s 到 %s 座標 %.2f, %.2f，來自 %s",
	
	["Mineral"] = "礦石",
	["Herb"] = "草藥",
	
	--["Gatherer"] = true,
} end)

L:RegisterTranslations("esES", function() return {
	["Added %s %s to %s at %.2f, %.2f from %s"] = "A\195\177adido %s %s a %s en %.2f, %.2f desde %s",
	
	["Mineral"] = "Mineral",
	["Herb"] = "Hierba",
	["Treasure"] = "Tesoro",
	["Gatherer"] = "Gatherer",
	["Fishing"] = "Pesca",
} end)

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

local zones = {
	[1] = {
		BZ["Ashenvale"],
		BZ["Azshara"],
		BZ["Darkshore"],
		BZ["Darnassus"],
		BZ["Desolace"],
		BZ["Durotar"],
		BZ["Dustwallow Marsh"],
		BZ["Felwood"],
		BZ["Feralas"],
		BZ["Moonglade"],
		BZ["Mulgore"],
		BZ["Orgrimmar"],
		BZ["Silithus"],
		BZ["Stonetalon Mountains"],
		BZ["Tanaris"],
		BZ["Teldrassil"],
		BZ["The Barrens"],
		BZ["Thousand Needles"],
		BZ["Thunder Bluff"],
		BZ["Un'Goro Crater"],
		BZ["Winterspring"],
-- new Kalimdor zones
                BZ["Azuremyst Isle"],
                BZ["Bloodmyst Isle"],
                BZ["The Exodar"],
	},
	[2] = {
		BZ["Alterac Mountains"],
		BZ["Arathi Highlands"],
		BZ["Badlands"],
		BZ["Blasted Lands"],
		BZ["Burning Steppes"],
		BZ["Deadwind Pass"],
		BZ["Dun Morogh"],
		BZ["Duskwood"],
		BZ["Eastern Plaguelands"],
		BZ["Elwynn Forest"],
		BZ["Hillsbrad Foothills"],
		BZ["Ironforge"],
		BZ["Loch Modan"],
		BZ["Redridge Mountains"],
		BZ["Searing Gorge"],
		BZ["Silverpine Forest"],
		BZ["Stormwind City"],
		BZ["Stranglethorn Vale"],
		BZ["Swamp of Sorrows"],
		BZ["The Hinterlands"],
		BZ["Tirisfal Glades"],
		BZ["Undercity"],
		BZ["Western Plaguelands"],
		BZ["Westfall"],
		BZ["Wetlands"],
-- new Eastern Continent zones
                BZ["Eversong Woods"],
                BZ["Ghostlands"],
                BZ["Silvermoon City"],
	},
-- new Outland zones
	[3] = {
                BZ["Blade's Edge Mountains"],
                BZ["Hellfire Peninsula"],
                BZ["Nagrand"],
                BZ["Netherstorm"],
                BZ["Shadowmoon Valley"],
                BZ["Shattrath City"],
                BZ["Terokkar Forest"],
                BZ["Zangarmarsh"],
	}
}
table.sort(zones[1])
table.sort(zones[2])
table.sort(zones[3])

function Cartographer_Import:OnEnable()
	self:TryImportGatherer()
	self:TryImportMapNotes()
        self:TryImportMetaMapNotes()
	self:Print("Done importing notes")
end

function Cartographer_Import:TryImportGatherer()
	local hasMining = Cartographer:HasModule(AceLibrary("Babble-Spell-2.2")["Mining"])
	local hasHerb = Cartographer:HasModule(AceLibrary("Babble-Spell-2.2")["Herbalism"])
	local hasFishing = Cartographer:HasModule(AceLibrary("Babble-Spell-2.2")["Fishing"])
	local hasTreasure = Cartographer:HasModule(L["Treasure"])
	
	if GatherItems then
		-- check type
		if GatherItems["dbVersion"] == nil then
			self:ParseOldDB(hasMining,hasHerb,hasFishing,hasTreasure)
		elseif GatherItems["dbVersion"] == 2 then
			self:ParseVer2DB(hasMining,hasHerb,hasFishing,hasTreasure)
		else
			self:Print("Cannot import Gatherer, Unknown DB version")
		end
	end
end

function Cartographer_Import:ParseOldDB(hasMining,hasHerb,hasFishing,hasTreasure)
	local gathererMineralsToCartographer = {
		["copper"] = "Copper",
		["tin"] = "Tin",
		["iron"] = "Iron",
		["iron"] = "Iron",
		["iron"] = "Iron",
		["silver"] = "Silver",
		["truesilver"] = "Truesilver",
		["gold"] = "Gold",
		["mithril"] = "Mithril",
		["thorium"] = "Thorium",
		["thorium (rich)"] = "Rich Thorium",
		["dark iron"] = "Dark Iron",

		["copper vein"] = "Copper",
		["tin vein"] = "Tin",
		["iron deposit"] = "Iron",
		["silver vein"] = "Silver",
		["truesilver deposit"] = "Truesilver",
		["gold vein"] = "Gold",
		["mithril deposit"] = "Mithril",
		["small thorium vein"] = "Thorium",
		["rich thorium vein"] = "Rich Thorium",
		["dark iron deposit"] = "Dark Iron",
	}

	local gathererHerbsToCartographer = {
		["arthas' tears"] = "Arthas' Tears",
		["black lotus"] = "Black Lotus",
		["blindweed"] = "Blindweed",
		["briarthorn"] = "Briarthorn",
		["bruiseweed"] = "Bruiseweed",
		["dreamfoil"] = "Dreamfoil",
		["earthroot"] = "Earthroot",
		["fadeleaf"] = "Fadeleaf",
		["firebloom"] = "Firebloom",
		["ghost mushroom"] = "Ghost Mushroom",
		["golden sansam"] = "Golden Sansam",
		["goldthorn"] = "Goldthorn",
		["grave moss"] = "Grave Moss",
		["gromsblood"] = "Gromsblood",
		["icecap"] = "Icecap",
		["khadgar's whisker"] = "Khadgar's Whisker",
		["kingsblood"] = "Kingsblood",
		["liferoot"] = "Liferoot",
		["mageroyal"] = "Mageroyal",
		["mountain silversage"] = "Mountain Silversage",
		["peacebloom"] = "Peacebloom",
		["plaguebloom"] = "Plaguebloom",
		["purple lotus"] = "Purple Lotus",
		["silverleaf"] = "Silverleaf",
		["stranglekelp"] = "Stranglekelp",
		["sungrass"] = "Sungrass",
		["swiftthistle"] = "Swiftthistle",
		["wild steelbloom"] = "Wild Steelbloom",
		["wintersbite"] = "Wintersbite",
		["wildvine"] ="Wildvine"
	}
	local gathererFishingToCartographer = {
		["floating wreckage"] = "Floating Wreckage",
		--["school"] = "School",
	}
	local gathererTreasureToCartographer = {
		["abercrombie's crate"] = "Abercrombie's Crate",
		["alexston's chest"] = "Alexston's Chest",
		["alliance chest"] = "Alliance Chest",
		["ammo crate"] = "Ammo Crate",
		["arena treasure chest"] = "Arena Treasure Chest",
		["armor crate"] = "Armor Crate",
	--	["atal'ai artifact"] = "Atal'ai Artifact",
		["barrel of melon juice"] = "Barrel Of Melon Juice",
		["barrel of milk"] = "Barrel Of Milk",
		["barrel of sweet nectar"] = "Barrel Of Sweet Nectar",
		["battered chest"] = "Battered Chest",
		["blood of heroes"] = "Blood Of Heroes",
		["bloodpetal sprout"] = "Bloodpetal Sprout",
		["box of assorted parts"] = "Box Of Assorted Parts",
		["broken barrel"] = "Broken Barrel",
		["caravan chest"] = "Caravan Chest",
		["chest of containment coffers"] = "Chest Of Containment Coffers",
	--	["cleansed songflower"] = "Cleansed Songflower",
		["crate of foodstuffs"] = "Crate Of Foodstuffs",
		["crate with holes"] = "Crate With Holes",
		["damaged chest"] = "Damaged Chest",
		["damaged crate"] = "Damaged Crate",
		["document chest"] = "Document Chest",
		["excavation supply crate"] = "Excavation Supply Crate",
		["felix's box"] = "Felix's Box",
		["felix's chest"] = "Felix's Chest",
		["food crate"] = "Food Crate",
		["giant clam"] = "Giant Clam",
		["gizmorium shipping crate"] = "Gizmorium Shipping Crate",
		["horde chest"] = "Horde Chest",
		["horde supply crate"] = "Horde Supply Crate",
	--	["janice's parcel"] = "Janice's Parcel",
	--	["joseph redpath's monument"] = "Joseph Redpath's Monument",
		["karnitol's chest"] = "Karnitol's Chest",
		["kerlonian's chest"] = "Kerlonian's Chest",
		["locked chest"] = "Locked Chest",
		["malem chest"] = "Malem Chest",
		["marshal haggard's chest"] = "Marshal Haggard's Chest",
		["marvon's chest"] = "Marvon's Chest",
	--	["pamela's doll's head"] = "Pamela's Doll's Head",
	--	["pamela's doll's right side"] = "Pamela's Doll's Right Side",
	--	["pamela's doll's left side"] = "Pamela's Doll's Left Side",
		["perrine's chest"] = "Perrine's Chest",
		["rusty chest"] = "Rusty Chest",
		["scattered crate"] = "Scattered Crate",
	--	["school"] = "School",
	--	["scourge cauldron"] = "Scourge Cauldron",
		["sealed barrel"] = "Sealed Barrel",
		["sealed supply crate"] = "Sealed Supply Crate",
		["shay's chest"] = "Shay's Chest",
		["solid chest"] = "Solid Chest",
		["stolen iron chest"] = "Stolen Iron Chest",
		["sunken chest"] = "Sunken Chest",
		["trelane's chest"] = "Trelane's Chest",
		["un'goro dirt pile"] = "Un'Goro Dirt Pile",
		["un'goro soil"] = "Un'Goro Dirt Pile",
		["water barrel"] = "Water Barrel",
		["weapon crate"] = "Weapon Crate",
		["worn wooden chest"] = "Worn Wooden Chest",	
		["box"] = "Box",
		["chest"] = "Chest",
		["giant clam"] = "Clam",
		["crate"] = "Box",
		["barrel"] = "Barrel",
		["cask"] = "Barrel",
		["shellfish trap"] = "Shellfish Trap",
		["blood of heroes"] = "Blood of Heroes",
		["footlocker"] = "Footlocker",
		["bloodpetal"] = "Bloodpetal Sprout",
		["power crystal"] = "Power Crystal",
	}
	
	for continent, cdata in pairs(GatherItems) do
		for zone, zdata in pairs(cdata) do
			-- fixes errored up import for gather data in the wrong zone
			if zone == 0 then zone = 1 end
			if continent == 0 then continent = 1 end
			-- end import fix
			local zname = BZ:GetReverseTranslation(zones[continent][zone])
			for item, idata in pairs(zdata) do
				if gathererMineralsToCartographer[item] and hasMining then
					for _,v in ipairs(idata) do
						if Cartographer_Notes:SetNote(zname, v.x/100, v.y/100, gathererMineralsToCartographer[item], "Mining") then
							self:Print(L["Added %s %s to %s at %.2f, %.2f from %s"], L["Mineral"], gathererMineralsToCartographer[item], zname, v.x, v.y, "Gatherer")
						end
					end
				elseif gathererHerbsToCartographer[item] and hasHerb then
					for _,v in ipairs(idata) do
						if Cartographer_Notes:SetNote(zname, v.x/100, v.y/100, gathererHerbsToCartographer[item], "Herbalism") then
							self:Print(L["Added %s %s to %s at %.2f, %.2f from %s"], L["Herb"], gathererHerbsToCartographer[item], zname, v.x, v.y, "Gatherer")
						end
					end
				elseif gathererFishingToCartographer[item] and hasFishing then
					for _,v in ipairs(idata) do
						if Cartographer_Notes:SetNote(zname, v.x/100, v.y/100, gathererFishingToCartographer[item], "Fishing") then
							self:Print(L["Added %s %s to %s at %.2f, %.2f from %s"], L["Fishing"], gathererFishingToCartographer[item], zname, v.x, v.y, "Gatherer")
						end
					end
				elseif gathererTreasureToCartographer[item] and hasTreasure then
					for _,v in ipairs(idata) do
						--if Cartographer_Notes:SetNote(zname, v.x/100, v.y/100, gathererTreasureToCartographer[item], "Treasure") then
						if Cartographer_Treasure:ImportNote(zname,v.x/100,v.y/100,gathererTreasureToCartographer[item]) then
							self:Print(L["Added %s %s to %s at %.2f, %.2f from %s"], L["Treasure"], gathererTreasureToCartographer[item], zname, v.x, v.y, "Gatherer")
						end
					end
				end
			end
		end
	end
end

function Cartographer_Import:ParseVer2DB(hasMining,hasHerb,hasFishing,hasTreasure)
	for continent, cdata in pairs(GatherItems) do
		if type(cdata) == "table" then
			for zone, zdata in pairs(cdata) do
				-- strip the _ out of name, and make title case
				local zname = self:ConvertZoneName(zone)
				
				for item, idata in pairs(zdata) do
					local itemName = self:FindGathererNodeName(item)
					if itemName == nil then itemName = select(1,GetItemInfo(item)) end
					if itemName == nil then
						--self:Print("Cant find item name for id ("..item..")") -- skip
					else
						local gType = idata["gtype"]
						for _,findData in pairs(idata) do
							if type(findData) == "table" then 
								if gType == "MINE" and hasMining then
									for _,v in ipairs(idata) do
										--self:Print(L["Added %s %s to %s at %.2f, %.2f from %s"], L["Mineral"], itemName, zname, v[1], v[2], "Gatherer")
										if Cartographer_Notes:SetNote(zname, v[1], v[2], itemName, "Mining") then
											self:Print(L["Added %s %s to %s at %.2f, %.2f from %s"], L["Mineral"], itemName, zname, v[1], v[2], "Gatherer")
										end
									end
								end
								if gType == "HERB" and hasHerb then
									for _,v in ipairs(idata) do
										--self:Print(L["Added %s %s to %s at %.2f, %.2f from %s"], L["Herb"], itemName, zname, v[1], v[2], "Gatherer")
										if Cartographer_Notes:SetNote(zname, v[1], v[2], itemName, "Herbalism") then
											self:Print(L["Added %s %s to %s at %.2f, %.2f from %s"], L["Herb"], itemName, zname, v[1], v[2], "Gatherer")
										end
									end
								end
						--[[		if hasFishing then  -- unknown GTYPE for fishing ?
									for _,v in ipairs(idata) do
										self:Print(L["Added %s %s to %s at %.2f, %.2f from %s"], L["Fishing"], itemName, zname, v[1], v[2], "Gatherer")
										if Cartographer_Notes:SetNote(zname, v[1], v[2], itemName, "Fishing") then
											self:Print(L["Added %s %s to %s at %.2f, %.2f from %s"], L["Fishing"], itemName, zname, v[1], v[2], "Gatherer")
										end
									end
								end ]]
								if gType == "OPEN" and hasTreasure then
									for _,v in ipairs(idata) do
										--self:Print(L["Added %s %s to %s at %.2f, %.2f from %s"], L["Treasure"], itemName, zname, v[1], v[2], "Gatherer")
										--if Cartographer_Notes:SetNote(zname, v.x/100, v.y/100, gathererTreasureToCartographer[item], "Treasure") then
										if Cartographer_Treasure:ImportNote(zname,v[1], v[2],itemName) then
											--self:Print(L["Added %s %s to %s at %.2f, %.2f from %s"], L["Treasure"], itemName, zname, v[1], v[2], "Gatherer")
										end
									end
								end
							end
						end
					end
				end
			end
		end
	end
end

-- very hacky way of making the zone correct
function Cartographer_Import:ConvertZoneName(zone)
	local zName = string.gsub(zone,"BLADES_EDGE_MOUNTAINS","BLADE'S_EDGE_MOUNTAINS")
	-- the gatherer lists BARRENS but should be "The Barrens" so we have to bodge it
	if zName == "BARRENS" then zName = "THE_BARRENS" end
	zName = string.gsub(self:titlecase(string.gsub(zName,"_"," "))," Of "," of ")
	
	return zName
end

function Cartographer_Import:FindGathererNodeName(nodeID)
	for name,id in pairs(Gatherer.Nodes.Names) do
		if id == nodeID then
			return name
		end
	end
end

function Cartographer_Import:TryImportMapNotes()
	if MapNotes_Data then
		for continent, cdata in pairs(MapNotes_Data) do
			for zone, zdata in pairs(cdata) do
				local zone = zones[continent][zone]

				--appears there may be some corrupt zones in the SV file. so zone will be nil here. we just skip those since there is no notes in these anyway.
				if zone then
					local zname = BZ:GetReverseTranslation(zone)
					for item, idata in pairs(zdata) do
						local note = {}
						note.icon = "Square"
						if idata.name and idata.name ~= "" then
							note.title = idata.name
						else
							note.title = "Imported note"
						end
						if idata.inf1 and idata.inf1 ~= "" then
							note.info = idata.inf1
						end
						if idata.inf2 and idata.inf2 ~= "" then
							note.info2 = idata.inf2
						end
						note.manual = true

						if Cartographer_Notes:SetNote(zname, idata.xPos, idata.yPos, note.icon, idata.creator, note) then
							self:Print(L["Added %s %s to %s at %.2f, %.2f from %s"], note.title, note.icon, zname, idata.xPos, idata.yPos, "MapNotes")
						end
					end
				end
			end
		end
	end
end

function Cartographer_Import:titlecase(str)
    local buf = {}
    for word in string.gmatch(str, "%S+") do          
        local first, rest = string.sub(word, 1, 1), string.sub(word, 2)
        table.insert(buf, string.upper(first) .. string.lower(rest))
    end    
    return table.concat(buf, " ")
end

function Cartographer_Import:ZoneExist(checkzone)
   for zone, zdata in pairs(zones) do
      for data,ddata in pairs(zdata) do
         if(zones[zone][data]==checkzone) then
            do return true end
         end
      end
   end
   return false;
end

function Cartographer_Import:TryImportMetaMapNotes()
  local hasIconPack = Cartographer:HasModule("Icons")
  if hasIconPack then
     local metaMapIconToCartographer = {
       [0] = "Yellow Square",
       [1] = "Red Square",
       [2] = "Purple Square",
       [3] = "Green Square",
       [4] = "Pink Square",
       [5] = "Yellow Star",
       [6] = "Red Star",
       [7] = "Purple Star",
       [8] = "Green Star",
       [9] = "Pink Star",
     }

     if MetaMap_Notes then
        self:Print("Import Meta Map Notes");
        for zone, zdata in pairs(MetaMap_Notes) do
           for data, ddata in pairs(zdata) do
              if(ddata and ddata['xPos'] and ddata['yPos'] and ddata['creator'] and ddata['name'] and ddata['icon']) then
                 if (self:ZoneExist(zone)) then
                    title=ddata['name'] or "";
                    info=ddata['inf1'] or "";
                    info2=ddata['inf2'] or "";
                    -- self:Print("Icon: "..metaMapIconToCartographer[ddata['icon']]);
                    if(Cartographer_Notes:SetNote(zone, ddata['xPos'], ddata['yPos'], metaMapIconToCartographer[ddata['icon']].."metamap_iconpack", ddata['creator'], 'title', title, 'info', info, 'info2', info2)) then
                       self:Print("Add "..zone.." "..ddata['xPos'].." ".. ddata['yPos'] .." "..metaMapIconToCartographer[ddata['icon']].."metamap_iconpack".." "..ddata['creator'].." title"..title..' info '..info..'info2'..info2);
                    end
                 end
              end
           end
        end
     end
  end
end
