require('idownx')

local function sup_default(url)
    if url:match("^http://sou.kuwo.cn/ws/NSearch?") then return true end
    if url:match("^http://www.kuwo.cn/zhuanji/%d+/") then return true end
    if url:match("^http://www.kuwo.cn/mingxing/") then return true end
    if url:match("^http://www.kuwo.cn/album/%d+/") then return true end
    return false
end

local function ana_default(url)
    local page = idown.requesturl(url)
    local div = page:match('<div class="listCont">(.-)</div>')
    for u in div:gmatch('href="(http://www.kuwo.cn/yinyue/%d+/)"') do
        idown.addtask(u)
    end
    return 200
end

local function sup_player(url)
    --http://player.kuwo.cn/webmusic/play?mid=120913%20387107%20674760%201011690%201076350%20480390%20814711%20529880
    if url:match("^http://player.kuwo.cn/webmusic/play") then return true end
end

local function ana_player(url)
    local p = urlparamdecode(url)
    local mid = p.mid
    local ids = split(mid, ' ')
        if #ids == 1 then
        local u = 'http://www.kuwo.cn/yinyue/'..ids[1]
        local result={
            Location = u,
        }
        retstr=idown.encode(result)
        return 301,retstr
    else
        for i = 1, #ids do
            if ids[i] ~= '' then 
            local u = 'http://www.kuwo.cn/yinyue/'..ids[i]
            idown.addtask(u)
            end
        end
        return 200
    end
end

local dispatcher = {
    --function issupport, analyze
    {sup_default,     ana_default},
    {sup_player,      ana_player},
}

function issupport(url)
    for i =1,#dispatcher do
        if dispatcher[i][1](url) then return true end
    end
    return false
end

function analyze(url)
    for i =1,#dispatcher do
        if dispatcher[i][1](url) then return dispatcher[i][2](url) end
    end
    return 
end