-- Title: Chuhaister
-- Author: w2unemdhysend
-- Description: Створіть базу даних англійською мовою, щоб покращити інтеграцію додатків

Chuhaister = {
    name = "Chuhaister",
    author = "w2unemdhysend",
	version = "0.1",
	displayName = "Chuhaister (PL patch TTC)",
	menuName = "ChuhaisterMenu",
	savedVars = {
		language = "",
		APIVersion = 0,
		UpdateNeeded = false,
		UpdateCompleted = false,
		Data = {
			Items =  {},
			Sets = {},
		},
	},
}

local function CloseMsgBox()
	ZO_Dialogs_ReleaseDialog("ChuhaisterDialog", false)
end

local function ShowMsgBox(title, msg, btnText, callback)
	local confirmDialog = 
	{
		title = { text = title },
		mainText = { text = msg },
		buttons = 
		{
			{
				text = btnText, 
				callback = callback
			}
		}
   }

   ZO_Dialogs_RegisterCustomDialog("ChuhaisterDialog", confirmDialog)
   CloseMsgBox()
   ZO_Dialogs_ShowDialog("ChuhaisterDialog")
end

-- ShowMsgBox("Chuhaister", "Необхідно оновити базу даних Chuhaister, натисніть "Гаразд", щоб продовжити", SI_DIALOG_CONFIRM)


function Chuhaister.getItemName(itemLink)
	local itemID = select(4, ZO_LinkHandler_ParseLink(itemLink))
	local itemType = GetItemLinkItemType(itemLink)
	if Chuhaister.savedVars.Data.Items[itemType] == nil then return nil end
	item=Chuhaister.savedVars.Data.Items[itemType][tonumber(itemID)]
	return item
end

function Chuhaister.Menu()
    local LAM = LibAddonMenu2
	local panelName = "ChuhaisterMenu"
    local panelData = {
        type = "panel",
        name = Chuhaister.displayName,
        displayName = Chuhaister.displayName,
        author = Chuhaister.author,
		version = Chuhaister.version,
        registerForRefresh = true,
        registerForDefaults = true,
    }
    LAM:RegisterAddonPanel(panelName, panelData)
	
    local optionsTable = {}

	table.insert(optionsTable, {
		type = "header",
		name = "Aktualizuj",
	})
 
 	table.insert(optionsTable, {
		type = "description",
		text = "Zaktualizuj bazę danych w razie problemów lub zaktualizuj wersję gry.",
		width = "half",
	})

	table.insert(optionsTable, {
		type = "button",
		name = "Aktualizuj",
		tooltip = "Zaktualizuj bazę danych w razie problemów lub zaktualizuj wersję gry.",
        func = function()
			Chuhaister.savedVars.UpdateNeeded = true
			Chuhaister.savedVars.UpdateCompleted = false
			Chuhaister.savedVars.language = zo_strformat("<<z:1>>", GetCVar("language.2"))
			SetCVar("language.2", "en")
		end,
		warning = "Ostrzeżenie:\nTa opcja automatycznie przeładuje interfejs użytkownika!",
		width = "half",
    })

    LAM:RegisterOptionControls(panelName, optionsTable)
end

function Chuhaister.Update()
	Chuhaister.savedVars.Data.Items =  {}
	Chuhaister.savedVars.Data.Sets = {}

	for itemId = 1, 300000 do
		local itemLink = ZO_LinkHandler_CreateLink('', nil, ITEM_LINK_TYPE, itemId, 364, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
		local itemName = GetItemLinkName(itemLink)
		
		if itemName and itemName ~= "" and not string.match(itemName, "_") then
			local itemType = GetItemLinkItemType(itemLink)
			local hasSet, setName, _, _, _, setId = GetItemLinkSetInfo(itemLink)

			if Chuhaister.savedVars.Data.Items[itemType] == nil then
				Chuhaister.savedVars.Data.Items[itemType] = {}
			end

			if hasSet then
				Chuhaister.savedVars.Data.Sets[setId] = setName
			end
			
			Chuhaister.savedVars.Data.Items[itemType][itemId] = ZO_CachedStrFormat("<<z:1>>", itemName)
		end
	end
	
end

local function OnActivated(eventCode)
    EVENT_MANAGER:UnregisterForEvent(Chuhaister.name, EVENT_PLAYER_ACTIVATED)

	if Chuhaister.savedVars.UpdateNeeded then
		Chuhaister.Update()
		Chuhaister.savedVars.UpdateNeeded = false
		Chuhaister.savedVars.UpdateCompleted = true
		Chuhaister.savedVars.APIVersion = GetAPIVersion()
		ReloadUI("ingame")
	end
	
	if Chuhaister.savedVars.UpdateCompleted then
		Chuhaister.savedVars.UpdateCompleted = false
		SetCVar("language.2", Chuhaister.savedVars.language)
	end

	if Chuhaister.savedVars.APIVersion ~= GetAPIVersion() then
		d("Baza danych \"Chuhaister\" musi zostać zaktualizowana!\n(operacja niezbędna dla poprawnego działania Tamriel Trade Centre ze spolszczeniem)\nOtwórz \"Ustawienia -> Dodatki -> Chuhaister\" i kliknij przycisk \"Aktualizuj\".")
	end
end

EVENT_MANAGER:RegisterForEvent(Chuhaister.name, EVENT_PLAYER_ACTIVATED, OnActivated)

local function OnLoaded(eventCode, addonName)
	if addonName == Chuhaister.name then
		EVENT_MANAGER:UnregisterForEvent(addonName, EVENT_ADD_ON_LOADED)
		
		Chuhaister.savedVars = ZO_SavedVars:NewAccountWide("ChuhaisterSavedVariables", 1, nil, Chuhaister.savedVars)

		if GetCVar("language.2") == "en" then
			return
		end
		
		Chuhaister.Menu()
	end
end

EVENT_MANAGER:RegisterForEvent(Chuhaister.name, EVENT_ADD_ON_LOADED, OnLoaded)