require('common')

function issupport(url)       
    if url:match("http://www.8535.org/") then return true end
    return false   
end

function analyze_page(url, files)
	local page = idown.requesturl(url)
	--print(page)
	local folder = page:match('var bookname = "(.-)"')
	local title = page:match('var chaptername = "(.-)"')
	local ids = page:match('outputImg%("(.-)|"')
	local chpid = page:match('var chapter_id = "(.-)"')
	print(ids)

	if ids then
		local url1 = page:match('var article_id = "(.-)"')
		local url2 = '/'..math.floor(tonumber(url1)/1000)
		local url3 = '/'..page:match('var article_id = "(.-)"')
		local url4 = '/'..page:match('var chapter_id = "(.-)"')
		local id_list = split(ids,"|")
		
		local content=''
		for i=1,#id_list do
				local url6 = math.floor(tonumber(id_list[i])/79);	
				local url7 = 'http://pic.8535.org'..url2..url3..url4.."/"..url6..".gif"
				print(url7)
				local file={
					realurl=url7,
					realname=folder..'\\'..chpid..'_'..i..".gif"
				}
				print(file.realname)
				table.insert(files, file)
				line = string.format('<img src="%s" /><br>', chpid..'_'..i..".gif")
				content = content..line
		end
		local file={
			content=title..'<br><hr>'..content,
			realname=folder..'\\'..chpid..".html"
		}
		table.insert(files, file)
	else
		local file={
					content=title..'<br><hr>'..page:match('src="/ad/gonggao.js"></script></div></div>(.-)<div id="divimage">'),
					realname=folder..'\\'..chpid..".html"
		}
		print(file.realname)
		table.insert(files, file)
	end
	return folder..'\\'..title
end

function getbooklist(baseurl,page,suburls)
	--<div class="booklist clearfix">
	local listdiv = page:match('<div class="booklist clearfix">(.-)</div>')
	print(listdiv)
	for pageurl in listdiv:gmatch('<a href="(.-)"') do
		pageurl = baseurl..pageurl
		table.insert(suburls, pageurl)
		print(pageurl)
	end
end

function analyze(url)
	local json = require('json')
	
	--区别是否是目录
	local pageid = url:match('(%d*.html)')
	print(pageid)
	if pageid == nil then
		--目录
		local page = idown.requesturl(url)
		local suburls = {}
		getbooklist(url,page,suburls)
		local div = page:match('<div class="booklist clearfix">(.-)</div>')
		div=div:gsub('</span>','</span><br>')
		local result = {}
		result.encode = 936
		result.title = page:match('<h1>(.-)</h1><h3>')
		result.files={
		[1]={
		content=div,
		realname=result.title.."\\list.htm",
		redown=1
		}
		}

		for i=1,#suburls do
			idown.addtask(suburls[i])
		end
		return 202, json:encode(result)
	else
		--单页
		local result = {}
		result.encode = 936
		result.files = {}
		result.title = analyze_page(url,result.files)

		return 202, json:encode(result)
	end
end