local curl = require "lcurl.safe"
local json = require "cjson.safe"

script_info = {
	["title"] = "NCCKL",
	["description"] = "http://so.ncckl.cn/",
	["version"] = "0.0.1",
}

function onSearch(key, page)
	local data = ""
	local c = curl.easy{
		url = "http://so.ncckl.cn/soYunPan/search",
		httpheader = {"Content-Type: application/x-www-form-urlencoded"},
		post = 1,
		postfields = "keyWord=" .. pd.urlEncode(key) .. "&pages=" .. page,
		timeout = 15,
		proxy = pd.getProxy(),
		writefunction = function(buffer)
			data = data .. buffer
			return #buffer
		end,
	}
	c:perform()
	c:close()
	return parse(data)
end

function onItemClick(item)
	return ACT_SHARELINK, item.url 
end

function parse(data)
	local result = {}
	local j = json.decode(data)
	if j == nil or j.body == nil or j.body == json.null then
		return result
	end
	for i, item in ipairs(j.body) do 
		local title = item["title"]
		local tooltip = string.gsub(title, "<b>(.-)</b>", "%1")
		title = string.gsub(title, "<b>(.-)</b>", "{c #ff0000}%1{/c}")
		table.insert(result, {["url"] = "https://pan.baidu.com/s/1" .. item["url"] .. " " .. item["password"], ["title"] = title, ["time"] = item["createDate"], ["showhtml"] = "true", ["tooltip"] = tooltip, ["check_url"] = "true"})
	end
	return result
end