require('zip')
require('common')
require('idownx')

function issupport(url)
    if url:match("^http://vod.kankan.com/") then return true end
    return false   
end

function GetMovieData(id)
    local luaurl = string.format('http://xmp.kankan.xunlei.com/movielua/%d/%d.lua.zip', math.floor(id/1000), id)
    print(luaurl)
    
    local page = idown.requesturl(luaurl)
    
    local path = string.format('.%stmp', os.tmpname())
    f = assert(io.open(path, 'wb'))
    
    f:write(page)
    io.close(f)
    
    zfile = assert(zip.open(path))
    flua = assert(zfile:open(string.format('%d.lua', id)))
    data = flua:read('*a')
    flua:close()
    zfile:close()
    
    os.remove(path)
    
    data = 'do\n--'..data
    --print(data)
    func = assert(loadstring(data))
    return func()
end

function GetServer(page)
    code = page:match('({ip:[^}]*})')
    if #code == 0 then return end
    
    code = string.gsub(code, ':', '=')
    code = 'data='..code..'return data'
    print(code)
    
    f = loadstring(code)
    server = f()
    
    return server
end

function GetParams(page)
    code = page:match('({param1:%d+,param2:%d+})')
    if #code == 0 then return end
        
    code = string.gsub(code, ':', '=')
    
    code = 'data='..code..'return data'
    print(code)
    
    f = loadstring(code)
    params = f()
    
    return params
end

function GetRealUrl(gcid)
    local cdnurl = string.format('http://web.cl.kankan.xunlei.com/getCdnresource_flv?&gcid=%s', string.upper(gcid))
    print(cdnurl)
    
    local req={}
    req.debug=1
    req.headers = {Accept=''}
    local page = idown.requesturl(cdnurl,'',idown.encode(req))
    print(page)
    
    local server = GetServer(page)
    local params = GetParams(page)
        
    local str = 'xl_mp43651'..params.param1..params.param2
    local key = idown.crypt.md5(str)
    local key1 = tostring(params.param2)
    local url = string.format('http://%s:%d/%s?key=%s&key1=%s', server.ip, server.port, server.path, key, key1)
    print(url)
    
    return url
end

function analyze(url)
    local json = require('json')

    print('-----------------------Enter analyze-----------------------')
    id = url:match("/v/%d+/(%d+)")
    subid = url:match("subid=(%d+)")
    if id == nil then return -2 end
    print('id:'..id)
    
    movie = GetMovieData(id)
    local index = 1
    if subid ~= id then
        for i=1,#movie do
            if movie[i].isubmovieid == tonumber(subid) then
                index = i
            end
        end
    end
    count = movie[index].Bitrate.icount
    playurl = movie[index].Bitrate[count].splayurl
    print(playurl) 

    t = split(playurl, '/')
    realurl = GetRealUrl(t[5])
    if #realurl == 0 then return -2 end
    
    suffix = getsuffix(getfilename(realurl))
    if movie.smoviename == movie[index].sname then 
	showname = movie.smoviename
    else
	showname = movie.smoviename..'-'..movie[index].sname
    end
    realfilename = string.format('%s(%s)%s', showname, movie[index].Bitrate[count].sbitratedesc, suffix)
    title = realfilename
    
    --range
    size = tonumber('0x'..t[7])
    start = 0
    realurl = string.format("%s&start=%d&end=%d&", realurl, start, size)
    print(realurl)
    
    local result = {}
    result.realurl = realurl
    result.title = title
    result.realname = realfilename
    result.encode = 65001
	
    retstr = json:encode(result)
    
    print('-----------------------Leave analyze-----------------------')
    return 1, retstr
end