#- Copyright 2013-2014 VMware, Inc.  All rights reserved.
#- VMware Confidential

require 'net/http'

module VAPI::Protocol

    class HttpProvider

        attr_accessor :uri, :http, :cookie

        def initialize(url)
            self.uri = URI.parse(url)
            self.http = Net::HTTP.new(uri.host, uri.port)
            self.cookie = ''
            #TODO: use this for a connection pool: http://rubydoc.info/gems/persistent_http/PersistentHTTP

            http.set_debug_output $stderr if ENV['DEBUG_HTTP']
            http.use_ssl = (uri.scheme == "https")
            #http.use_ssl = true
            #if :ssl_verify
            #  http.verify_mode = OpenSSL::SSL::VERIFY_PEER
            #  http.cert = OpenSSL::X509::Certificate.new(pem)
            #  http.key = OpenSSL::PKey::RSA.new(pem)
            #else
            http.verify_mode = OpenSSL::SSL::VERIFY_NONE
            #end
            #http.start
            VAPI.log.debug "uri: #{uri}"
        end

        # The method used to send request to the server
        def do_request(content_type, content)
            VAPI.log.debug "request: #{content}"

            request = Net::HTTP::Post.new(uri.path) #URI.encode(uri))
            request.add_field('Content-Type', content_type)
            request.add_field('Cookie', self.cookie)
            request.body = content
            #Investigate EOF error with http.request
            #response = http.request(request)
            response = http.start {|http| http.request request }
            #VAPI.log.debug "response status: #{response.status}"
            # cookie = response.getheader('Set-Cookie')
            # self.cookie = cookie if cookie

            VAPI.log.debug "response (#{response.code}, #{response.message}): #{response.body}"
            response.body
        end

    end

end
