-- Protects a string that will be wrapped in wiki italic markup '' ... ''
local function safeforitalics( str )
    --[[ Note: We can not use <i> for italics, as the expected behavior for
    italics specified by ''...'' in the title is that they will be inverted
    (i.e. unitalicized) in the resulting references.  In addition, <i> and ''
    tend to interact poorly under Mediawiki's HTML tidy. ]]

    if str == nil or str == '' then
        return str;
    else
        if str:sub(1,1) == "'" then str = "<span />" .. str; end
        if str:sub(-1,-1) == "'" then str = str .. "<span />"; end
        return str;
    end
end


local function track(args, i)
    local titolo = args["Titolo" .. i] or ""
    if  titolo ~=""  then
        local row_elements = {}
        table.insert(row_elements, '<li value="' .. tostring(i) .. '">')
        interprete = args["Interprete" .. i] or ""
        if interprete ~= "" then table.insert(row_elements, interprete .. " – ") end
        table.insert(row_elements, "''" .. safeforitalics(titolo) .. "''")
        local featuring = args["Featuring" .. i] or ""
        if featuring ~= "" then table.insert(row_elements, " <small>(feat. " .. featuring .. ")</small>") end
        local note = args["Note" .. i] or ""
        if note ~= "" then table.insert(row_elements, " <small>(" .. note ..  ")</small>")  end
        local string_durata = args["Durata" .. i]
        if string_durata then
            local string_minuti, string_secondi = mw.ustring.match(string_durata, "(%d+):(%d%d)")
            minuti = tonumber(string_minuti) or 0
            secondi = tonumber(string_secondi) or 0
        else
            minuti = tonumber(args["Minuti" .. i]) or 0
            secondi = tonumber(args["Secondi" .. i]) or 0
        end
        local durata = minuti * 60 +  secondi
        if durata > 0  then
            table.insert(row_elements, " – ")
            table.insert(row_elements, string.format("%d:%02.f", minuti, secondi))
        end
        local AutoreTesto = args["Autore testo" .. i] or ""
        local AutoreMusica = args["Autore musica" .. i] or ""
        local AutoreTestoeMusica = args["Autore testo e musica" .. i] or ""
        local edizioni = args["Edizioni" .. i] or ""
        local no_autore = false
        if AutoreTestoeMusica ~= "" then
            table.insert(row_elements, " <small>(" .. AutoreTestoeMusica )
        elseif AutoreTesto ~= "" then
            table.insert(row_elements, " <small>(")
            if AutoreMusica ~= "" then
                table.insert(row_elements, AutoreTesto ..  " – " .. AutoreMusica)
            else
                table.insert(row_elements, AutoreTesto)
            end
        elseif AutoreMusica ~= "" then
            table.insert(row_elements, " <small>(" .. AutoreMusica)
        else
            no_autore = true
        end
        if edizioni ~= "" then
            if no_autore then
                table.insert(row_elements, " <small>(")
            else
                table.insert(row_elements, ";")
            end
            table.insert(row_elements, "edizioni musicali " .. edizioni .. ")</small>")
        elseif not no_autore then
            table.insert(row_elements, ")</small>")
        end
        local extra = args["Extra" .. i] or ""
        if extra ~= "" then table.insert(row_elements, " – " .. extra) end
        table.insert(row_elements, "</li>\n")
        local ListaMedley = args["ListaMedley" .. i] or ""
        if ListaMedley ~= "" then table.insert(row_elements, '<div style="padding: 0.3em 0px 0.5em 2.5em;">\n' .. ListaMedley .. '</div>')  end
        return table.concat(row_elements), durata
    else
        return nil
    end
end

local function componi_tracce(args, primo_titolo)
    -- compone testata
    local tracks = {}
    local testata = ""
    local noautore = false
    local autoreTestoeMusica = args["Autore testi e musiche"] or ""
    if autoreTestoeMusica ~= "" then
        testata = "Testi e musiche di " .. autoreTestoeMusica
    else
        autoreTesti = args["Autore testi"] or ""
        autoreMusiche = args["Autore musiche"] or ""
        if autoreTesti ~= "" then
            testata = "Testi di " .. autoreTesti
            if autoreMusiche ~= "" then testata = testata .. ", musiche di " .. autoreMusiche end
        elseif autoreMusiche ~= "" then
            testata = "Musiche di " .. autoreMusiche
        else
            noAutore = true
        end
    end
    local edizioni = args["Edizioni"] or ""
    if edizioni ~= "" then
        if noAutore then
            testata = "Edizioni musicali " .. edizioni .."."
        else
            testata = testata .. "; edizioni musicali " .. edizioni .. "."
        end
    elseif not noAutore then
        testata = testata .. "."
    end
    table.insert(tracks, testata)
    -- compone la lista dei parametri
    local i = primo_titolo
    table.insert(tracks, "<ol>")
    local visualizza_durata = args["Visualizza durata totale"] or ""
    local durata = 0 
    local somma_durata = false
    if visualizza_durata == "si" then somma_durata = true end
    --estrae le tracce dai parametri e inserisci i valori nella tabella tracks
    while true do
        local new_track, durata_track = track(args, i)
        if new_track==nil then break end
        table.insert(tracks, new_track)
        if somma_durata then durata = durata + durata_track end
        i = i + 1
    end
    table.insert(tracks, "</ol>")
    if somma_durata then
        table.insert(tracks, "Durata totale: " .. string.format("%d:%02.f", math.floor(durata/60) , durata % 60) .. "</p>")
    end
    return table.concat(tracks, "\n")
end

local p = {}

function p.tracce(frame)
    -- ottiene i parametri del template originale
    local pframe = frame:getParent()
    -- estrae tutti i parametri e li memorizza in una tabella (pframe ritorna una pseudotabella, vedi documentazione)
    local args = {}
    local primo_titolo
    local inizio, fine, numero_titolo
    for k, v in pairs( pframe.args ) do
        args[k] = v
        inizio, fine = string.find(k, "Titolo", 1, true)
        if fine ~= nil then
            numero_titolo = tonumber(string.sub(k, fine+1))
            if numero_titolo ~= nil and (not primo_titolo  or numero_titolo < primo_titolo) then
                primo_titolo = numero_titolo
            end
        end
    end
    if primo_titolo then
        return componi_tracce(args, primo_titolo)
    else
        return ""
    end
end

local conversion_table = {
    ['all_writing'] = 'Autore testi e musiche',
    ['all_lyrics'] = 'Autore testi',
    ['all_music'] = 'Autore musiche',
}

function p.en_tracks(frame)
    local pframe = frame:getParent()
    -- estrae tutti i parametri e li memorizza in una tabella (pframe ritorna una pseudotabella, vedi documentazione)
    local rows = { '{{Tracce'}
    for k,v in pairs( pframe.args) do
        if conversion_table[k] then 
            table.insert(rows, '|' .. conversion_table[k] .. '=' .. v)
        end
    end
    table.insert(rows, '}}')
    return table.concat(rows, '\n')
end




return p