# signature { license=0, seed=277031123, key="d6230db2a9bf83f78798f41b8cb508d7" }
-- ----------------------------------------------------------------------------



local socket = require 'socket'
local format = string.format

local webpro = {}




local requestf = '%s /%s HTTP/1.1\r\n%sContent-Length: %d\r\n\r\n%s'
function webpro.request( method, resource, text, headers, port )
	local request = requestf:format( method, resource, headers or '', #text, text )

	local xmlport = require( 'xmlpro.core' ).port


	local tls = xmlport == 0
	if tls then
		port = port or webpro.port or 443
	else
		port = xmlport
	end

	local sock = socket.connect( '127.0.0.1', port )

	if tls then

		local ok, err
		sock, err = require( 'ssl' ).wrap( sock, { protocol='tlsv1_2', mode='client', verify='none' } )
		if not sock then error( err ) end
		ok, err = sock:dohandshake()
		if not ok then return nil, err end
	end

	sock:send( request )

	local response
	local status = sock:receive():match( ' (%d%d%d)' )

	if '200' == status then
		local len = 0
		repeat
			local line = sock:receive()
			len = line:lower():match( '^content%-length:%s*(%d+)' ) or len
		until line == ''

		response = sock:receive( tonumber( len ) ) or ''
	end
	sock:close()

	return response, status
end

webpro.get = function( resource, headers, port )
	return webpro.request( 'GET', resource, '', headers, port )
end

webpro.post = function( resource, text, headers, port )
	return webpro.request( 'POST', resource, text, headers, port )
end

webpro.login = function( name, password )
	local text = format( 'formData=0%%12userName%%3D%s%%12language%%3DonChange%%3D%%12password%%3D%s', name, password )
	local response = webpro.post( 'Login.htm%3FsessionId%3D%26LOGIN%28%29', text )
	webpro.sessionid = response:match( 'g_sessionId="([^"]*)";' )

	return webpro.sessionid
end

webpro.logout = function( sessionid )
	webpro.get( format( 'Home.htm%%3FsessionId%%3D%s%%26LOGOUT%%28%%29', sessionid or webpro.sessionid ) )
end

local uploadLicTemplate =
'----snip--\r\n\z
Content-Disposition: form-data; name="hasDataChanged"\r\n\r\n0\r\n----snip--\r\n\z
Content-Disposition: form-data; name="hwKeyCode"\r\n\r\n%s\r\n----snip--\r\n\z
Content-Disposition: form-data; name="licenseFileName"; filename="lms.lic"\r\n\z
Content-Type: application/octet-stream\r\n\r\n%s\r\n----snip----\r\n'


local uploadLicUrl = ( os.uname == 'linux' ) and 'PyxisMaLicenseUpload' or 'LicenseRegistration'




webpro.uploadLIC = function( lic, sessionid )
	sessionid = sessionid or webpro.sessionid
	local resource = format( '%s.htm?sessionId=%s&UPLOAD_LICENSE_FILE()', uploadLicUrl, sessionid )
	local headers = 'Content-Type: multipart/form-data; boundary=--snip--\r\n'
	local text = format( uploadLicTemplate, cfg.HardwareKeyCode, lic )
	local response, status = webpro.post( resource, text, headers )


	return (response or '' ):match( ' class="errorText[^>]*>([^<]*)<' ) or 'HTTP status:'..status
end

return webpro
