local SousChef = SousChef

local u =  SousChef.Utility

function u.GetItemID(link)
    if link == "" or not link then return -1 end
    local itemid = select(4,ZO_LinkHandler_ParseLink(link))
	return tonumber(itemid)
end

function u.EndsWith(String,End)
   return End=='' or string.sub(String,-string.len(End))==End
end

function u.StartsWith(String,Start)
    return Start=='' or string.sub(String, 1, string.len(Start))==Start
end

local languageElements = {"de ", "à ", "la ", }
local separators = {"%^[%a:]+", "-", " " }

function u.StripLanguageIdentifiers(entry)
    if not entry or entry == "" then return "" end
    for _,v in pairs(languageElements) do
        entry = entry:gsub(v, "")
    end
    return entry
end

function u.Compress(entry)
    if not entry or entry == "" then return "" end
    for _,v in pairs(separators) do
        entry = entry:gsub(v, "")
    end
    return entry
end

function u.CleanString(entry)
    if not entry or entry == "" then return "" end
    if SousChef.settings.experimentalMatch then
        entry = u.StripLanguageIdentifiers(entry)
    end
    return u.Compress(entry):lower()
end

function u.MatchesRecipe(entry)
    return u.CleanString(entry):find(u.CleanString(GetString(SI_ITEMTYPE29)))
end

function u.TableKeyConcat(t)
    local tt = {}
    for k in pairs(t) do tt[#tt+1]=k end
    return table.concat(tt, ", ")
end

function u.MatchInCookbook(name)
    name = u.CleanString(name)
    for recipe,known in pairs(SousChef.Cookbook) do
        if u.StartsWith(name,recipe) or u.EndsWith(name, recipe) then
            local difference =  (#recipe + #u.CleanString(GetString(SI_ITEMTYPE29)) - #name)
            if  difference < 3 and difference > -3 then
                return known
            end
        end
    end
	return nil
end

function u.MatchInGlobalCookbook(name)
    name = u.CleanString(name)
    for recipe,known in pairs(SousChef.settings.Cookbook) do
        if u.StartsWith(name,recipe) or u.EndsWith(name, recipe) then
            local difference =  (#recipe + #u.CleanString(GetString(SI_ITEMTYPE29)) - #name)
            if  difference < 3 and difference > - 3 then
                return known
            end
        end
    end
    return nil
end

function u.MatchInIgnoreList(name)
    name = u.CleanString(name)
    for recipe in pairs(SousChef.settings.ignoredRecipes) do
        if u.CleanString(recipe) == name then return true end
    end
    return false
end

function u.TableLength(t)
	if type(t) ~= "table" then return #t end
	local n = 0
	for k, v in pairs(t) do
		n = n + 1
	end
	return n
end