local list = require('Module:ACGaward/list').list

local getArgs = require('Module:Arguments').getArgs

local p = {}

local function makeInvokeFunc(funcName)
    return function(frame)
        local args = getArgs(frame)
        return p[funcName](args)
    end
end

p.level = makeInvokeFunc('_level')
function p._level(args)
    local username = string.match(tostring(mw.title.getCurrentTitle().text), '^[^/]+')
    if args.level then
        return args.level
    end
    for _, value in ipairs(list) do
        if value[1] == username then
            return math.floor(value[2] / 10)
        end
    end
    return args[1]
end

p.ranking = makeInvokeFunc('_ranking')
function p._ranking(args)
    local tab, tabList, scoreLessThenTenCounter = '', {}, {}
    for i = 1, 9 do
        scoreLessThenTenCounter[i] = 0
    end
    table.sort(list, function(a, b)
        return (a[2] > b[2])
    end)

    -- 50级以上目前总共只有3人,为避免分类过于琐碎,不再细分60级、70级
    table.insert(tabList, "'''50級或以上維基ACG創作獎'''" .. '\n')
    for key, value in ipairs(list) do
        if value[2] < 500 and list[key - 1][2] >= 500 then
            table.insert(tabList, "'''40至49級維基ACG創作獎'''" .. '\n')
        elseif value[2] < 400 and list[key - 1][2] >= 400 then
            table.insert(tabList, "'''30至39級維基ACG創作獎'''" .. '\n')
        elseif value[2] < 300 and list[key - 1][2] >= 300 then
            table.insert(tabList, "'''20至29級維基ACG創作獎'''" .. '\n')
        elseif value[2] < 200 and list[key - 1][2] >= 200 then
            table.insert(tabList, "'''10至19級維基ACG創作獎'''" .. '\n')
        elseif value[2] < 100 and list[key - 1][2] >= 100 then
            table.insert(tabList, "'''5至9級維基ACG創作獎'''" .. '\n')
        elseif value[2] < 50 and list[key - 1][2] >= 50 then
            table.insert(tabList, "'''4級維基ACG創作獎'''" .. '\n')
        elseif value[2] < 40 and list[key - 1][2] >= 40 then
            table.insert(tabList, "'''3級維基ACG創作獎'''" .. '\n')
        elseif value[2] < 30 and list[key - 1][2] >= 30 then
            table.insert(tabList, "'''2級維基ACG創作獎'''" .. '\n')
        elseif value[2] < 20 and list[key - 1][2] >= 20 then
            table.insert(tabList, "'''1級維基ACG創作獎'''" .. '\n')
        elseif value[2] < 10 and list[key - 1][2] >= 10 then
            table.insert(tabList, "'''未滿1級維基ACG創作獎'''" .. '\n')
        end
        if value[2] < 10 then
            for i = 1, 9 do
                if value[2] == i then
                    scoreLessThenTenCounter[i] = scoreLessThenTenCounter[i] + 1
                end
            end
        else
            local user = string.format('[[User:%s|%s]]', value[1], value.nickname or value[1])
            table.insert(tabList, '# ' .. user .. ':' .. value[2] .. '分' .. '\n')
        end
    end
    local text = table.concat(tabList)
    for i = 9, 1, -1 do
        text = text .. '# ' .. scoreLessThenTenCounter[i] .. '名維基人:' .. i .. '分' .. '\n'
    end
    return mw.getCurrentFrame():expandTemplate { title = 'Div col', args = { colwidth = '16em' } } .. '\n' .. text .. mw.getCurrentFrame():expandTemplate { title = 'Div col end' }
end

p.lv = makeInvokeFunc('_lv')
function p._lv(args)
    -- Code for the second function goes here.
    local tab, tabList = '', {}
    table.sort(list, function(a, b)
        return (a[2] > b[2])
    end)
    local scoreLessThenTenCounter = 0
    for _, value in ipairs(list) do
        if value[2] < 10 then
            scoreLessThenTenCounter = scoreLessThenTenCounter + 1
        else
            local user = string.format('[[User:%s|%s]]', value[1], value.nickname or value[1])
            table.insert(tabList, '*' .. math.floor(value[2] / 10) .. '級:' .. user .. '\n')
        end
    end
    local text = table.concat(tabList) .. '* 另有' .. scoreLessThenTenCounter .. '名维基人不滿1級ACG創作貢獻獎' .. '\n'
    return mw.getCurrentFrame():expandTemplate { title = 'Div col', args = { colwidth = '16em' } } .. '\n' .. text .. mw.getCurrentFrame():expandTemplate { title = 'Div col end' }
end

p.all = makeInvokeFunc('_all')
function p._all(args)
    local tabList = {}
    for _, v in ipairs(list) do
        table.insert(tabList, '* ' .. v[1] .. '|' .. v[2])
    end
    return table.concat(tabList, '\n')
end

p.diff = makeInvokeFunc('_diff')
function p._diff(args)
    local new_list = list
    local old_list = require('Module:ACGaward/list/old').list

    local function get_score(list, username)
        for _, v in pairs(list) do
            if v[1] == username then
                return v[2]
            end
        end
        return 0
    end

    -- New scores vs. old scores
    local new_vs_old = {}
    for _, v in pairs(new_list) do
        local user = v[1]
        local new_score = v[2]
        local old_score = get_score(old_list, user)
        local diff = new_score - old_score

        if diff ~= 0 then
            table.insert(new_vs_old, { user, diff, new_score })
        end
    end
    table.sort(new_vs_old, function(a, b)
        return a[2] > b[2]
    end)

    local function nowiki(text)
        return mw.getCurrentFrame():callParserFunction( '#tag:nowiki', text )
    end

    local report_new_vs_old = {}
    for _, v in pairs(new_vs_old) do
        local str = '# ' .. nowiki('* [[User:' .. v[1] .. '|' .. v[1] .. ']]:共得' .. v[2] .. '分' ..
                '<small>(累計分數' .. v[3] .. '分)</small>')
        table.insert(report_new_vs_old, str)
    end

    -- Old scores vs. new scores
    local old_vs_new = {}
    for _, v in pairs(old_list) do
        local user = v[1]
        local new_score = get_score(new_list, user)
        local old_score = v[2]
        local diff = new_score - old_score

        if diff < 0 then
            table.insert(old_vs_new, { user, diff, new_score })
        end
    end
    table.sort(old_vs_new, function(a, b)
        return a[2] < b[2]
    end)

    local report_old_vs_new = {}
    for _, v in pairs(old_vs_new) do
        local str = '# ' .. nowiki('* [[User:' .. v[1] .. '|' .. v[1] .. ']]:共得' .. v[2] .. '分' ..
                '<small>(累計分數' .. v[3] .. '分)</small>')
        table.insert(report_old_vs_new, str)
    end

    -- result
    local res = {}
    table.insert(res, table.concat(report_new_vs_old, '\n'))
    if #report_old_vs_new > 0 then
        table.insert(res, '異常分數變化(如用戶更名)')
        table.insert(res, table.concat(report_old_vs_new, '\n'))
    end
    return table.concat(res, '\n')
end

return p