local _, addon = ...

local function BuildIndex(text)
    local numberMarks = text:gsub("%d+%.?%d*", "#?")
    local normalized = numberMarks:gsub('"', "'")
    return normalized
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.m or nil
    if text then
        return FillPlaceholders(FillNumbers(text, message))
    else
        return nil
    end
end
addon.API.GetSpeech = GetSpeech