local _, addon = ...

local CzechOriginalMode = {
  CZ_ORIG = 1,
  CZ = 2,
  ORIG = 3,
  ORIG_CZ = 4,
}

local function GetCzechOriginalOptions()
    local container = Settings.CreateControlTextContainer()
    container:Add(CzechOriginalMode.CZ_ORIG, "Preklad (Original)")
    container:Add(CzechOriginalMode.ORIG_CZ, "Original (Preklad)")
    container:Add(CzechOriginalMode.CZ, "Pouze preklad")
    container:Add(CzechOriginalMode.ORIG, "Pouze original")
    return container:GetData()
end
addon.API.GetCzechOriginalOptions = GetCzechOriginalOptions

local function CzechOriginalParser(text)
  local parts = {}
    local pos = 1

    while true do
      local matchStart,
            matchEnd,
            textBefore,
            czechText,
            originalText =
        string.find( text,"(.-)%{t1%}(.-)%{/t1%}%s*%{t2%}(.-)%{/t2%}", pos)

      if not matchStart then
        table.insert(parts, { text = string.sub(text, pos) })
        break
      end

      if textBefore ~= "" then
        table.insert(parts, { text = textBefore })
      end

      table.insert(parts, {
        cz   = czechText,
        orig = originalText
      })

      pos = matchEnd + 1
    end

    return parts
end

local function CzechOriginalBuild(parsed, mode)
  local out = {}

  for _, part in ipairs(parsed) do
    if part.text then
      table.insert(out, part.text)
    else
      if mode == CzechOriginalMode.CZ_ORIG then
        table.insert(out, part.cz .. " (" .. part.orig .. ")")
      elseif mode == CzechOriginalMode.CZ then
        table.insert(out, part.cz)
      elseif mode == CzechOriginalMode.ORIG then
        table.insert(out, part.orig)
      elseif mode == CzechOriginalMode.ORIG_CZ then
        table.insert(out, part.orig .. " (" .. part.cz .. ")")
      end
    end
  end

  return table.concat(out)
end

local function GetCzechOriginalText(text)
  local mode = CzechQuestsAddon_Store.config.QUEST_TEXT_CZECH_ORIGINAL_FORMAT

  local parsed = CzechOriginalParser(text)
  local result = CzechOriginalBuild(parsed, mode)

  return result
end
addon.API.GetCzechOriginalText = GetCzechOriginalText