module(...,package.seeall)
require"misc"
--sslͻʹca֤У˵֤ʱжϷ֤ЧڣԱ뱣֤ģʱȷ
--ntpģԶͬʱ䵽ģ
require"ntp"
require"https"
require"common"

local ssub,schar,smatch,sbyte,slen = string.sub,string.char,string.match,string.byte,string.len
local ADDR,PORT ="36.7.87.100",4434
local httpclient

--[[
print
  ӡӿڣļедӡtestǰ׺
  
ֵ
]]
local function print(...)
	_G.print("test",...)
end


--[[
rcvcb
  ջص
  resultݽս(˲Ϊ0ʱļ)
				0:ɹ
				2:ʾʵ峬ʵʵ壬󣬲ʵ
				3:ճʱ
		statuscodehttpӦ״̬룬stringͻnil
		headhttpӦͷݣtableͻnil
		bodyhttpӦʵݣstringͻnil
ֵ
]]
local function rcvcb(result,statuscode,head,body)
	print("rcvcb",result,statuscode,head,slen(body or ""))
	
	if result==0 then
		if head then
			print("rcvcb head:")
			--ӡͷΪײ֣ӦֵΪײֵֶ
			for k,v in pairs(head) do		
				print(k..": "..v)
			end
		end
		print("rcvcb body:")
		print(body)
	end
	
	httpclient:disconnect(discb)
end

--[[
rcvcbfile
  ջصļ
  resultݽս(˲Ϊ0ʱļ)
				0:ɹ
				2:ʾʵ峬ʵʵ壬󣬲ʵ
				3:ճʱ
		statuscodehttpӦ״̬룬stringͻnil
		headhttpӦͷݣtableͻnil
		filename: ļ·
ֵ
]]
local function rcvcbfile(result,statuscode,head,filename)
	print("rcvcbfile",result,statuscode,head,filename)	
	
	if result==0 then
		local filehandle = io.open(filename,"rb")
		if not filehandle then print("rcvcbfile open file error") return end
		local current = filehandle:seek()
		local size = filehandle:seek("end")
		filehandle:seek("set", current)
		--ļ
		print("rcvcbfile size",size)
		
		--ļݣļ̫һԶļݿܻڴ治㣬ִζԱ
		print("rcvcbfile content:\r\n")
		if size<=4096 then
			print(filehandle:read("*all"))
		else
			
		end
		
		filehandle:close()
	end
	--ļʹ֮ԺҪɾ
	if filename then os.remove(filename) end
	
	httpclient:disconnect(discb)
end

--[[
connectedcb
  SOCKET connected ɹص
  
ֵ
]]
local function connectedcb()
	--[[ô˺Żᷢͱ,request(cmdtyp,url,head,body,rcvcb),صrcvcb(result,statuscode,head,body)
		url·"/XXX/XXXX"headΪʽ{"Connection: keep-alive","Content-Type: text/html; charset=utf-8"}ע:
		һոbodyҪݣΪַ͡
	]]
	httpclient:request("GET","/",{},"",rcvcb)
	--httpclient:request("GET","/",{},"",rcvcbfile,"download.bin")
end 

--[[
sckerrcb
  SOCKETʧܻص
  
		rstringͣʧԭֵ
		CONNECT: socketһֱʧܣٳԶ
		SENDsocketʧܣٳԶ
ֵ
]]
local function sckerrcb(r)
	print("sckerrcb",r)
	if r=="CONNECT" then
		--http.luaѾϿӣԼ󣬴˴ֱӵconnect()ֱ
	elseif r=="SEND" then
		--http.luaзʧܣûжϿӣ˴ҪԼƶϿӣȻdiscb߼
		httpclient:disconnect(discb)
	end
end
--[[
connect
ܣӷ

	 connectedcb:ӳɹص
	 sckerrcbhttp libsocketһֱʧܻ߷GETPOSTʧʱԶǵsckerrcb
أ
]]
function connect()
	httpclient:connect(connectedcb,sckerrcb)
end
--[[
discb
  HTTPӶϿĻص
  		
ֵ
]]
function discb()
	print("http discb")
	--20½HTTP
	sys.timer_start(connect,20000)
end

--[[
http_run
  httpͻˣ
  		
ֵ
]]
function http_run()
	--ΪhttpЭڡTCPЭ飬ԲشPROT
	httpclient=https.create(ADDR,PORT)
	--verifysvrcertsУ֤CA֤ļ (Base64 X.509ʽ)
	--clientcertͻ˵֤ļ (Base64 X.509ʽ)
	--clientkeyͻ˵RSA PRIVATE KEY˽Կļ(Base64 X.509ʽ)
	httpclient:configcrt({verifysvrcerts={"ca.crt"},clientcert="client.crt",clientkey="client.key"})
	--httpclient:setconnectionmode(true)
	--http
	connect()	
end


--ú
http_run()



