# signature { license=0, seed=277031123, key="28a119f38e0f3acd8f4fd332378ed451" }
local socket = require 'socket'
local format = string.format

local _M = require 'xmlpro.core'
_M._VERSION   = "XmlPRO 1.0.0"
_M.authorization = 'dGVjaDoxMjM0NTY3OA=='

_M.login = function( name, password )
	local b64 = require( 'mime' ).b64
	_M.authorization = b64(name..':'..password)
end




_M.post = function( text, port )
	local request = format( 'POST /dbms.xml HTTP/1.1\r\nAuthorization: Basic %s\r\nContent-Length: %d\r\n\r\n%s',
		_M.authorization, #text, text )


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

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

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

	s:send( request )

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

		response = s:receive( tonumber( len ) )
	end
	s:close()
	return response, status
end

return _M
