local _, addon = ...

local function BuildIndex(text)
    local playerName = UnitName("player")

    local formatted = text:gsub("%d+%.?%d*", "#?")
    formatted = string.gsub(formatted, playerName, '<name>');
    formatted = formatted:gsub('"', "'")

    return formatted
end

local function FillNumbers(text, sourceText)
    local numbers = {}
    local currentIndex = 1

    for num in sourceText:gmatch("%d+%.?%d*") do
        table.insert(numbers, num)
    end

    local replacedText = text:gsub("#%?", function()
        local n = numbers[currentIndex]
        currentIndex = currentIndex + 1
        return n or "?"
    end)

    return replacedText
end

local function FillPlaceholders(text)
    if text == nil then
        return text
    end

    local playerName = UnitName("player")

    local formatted = text;
    formatted = string.gsub(formatted, '<name>', playerName);

    return formatted
end

local function GetSpeech(message)
    local index = BuildIndex(message)
    local speech = addon.data.speech[index];
    local text = speech and speech.text or nil
    if text then
        local formatted = FillNumbers(text, message)
        formatted = FillPlaceholders(formatted)
        formatted = addon.API.GetCzechOriginalText(formatted)
        return formatted
    else
        return nil
    end
end
addon.API.GetSpeech = GetSpeech