require "base64"
require 'net/http'

module Goalmouth
  module Securetrading

    class Connection

        attr_accessor :response

        def initialize(options)

            @api_url = "https://webservices.securetrading.net:443/"
            @options = options
            @response = nil
        end

        def perform

            if request_valid?

                make_request
            end
        end

        private 

        def build_xml

            raise "Overwrite this method in a subclass to build the required XML."
        end

        def request_type

            raise "Overwrite this method in a subclass to return the relevant request type."            
        end

        def request_valid?

            unless @options.key?(:username) || @options.key?(:password) || @options.key?(:site_reference)

                raise "Username, password and site reference are required."
            end
            return true
        end

        def make_request()

            xml = build_xml()
            @response = post(xml)
        end

        def post(data)

            creds = "#{@options[:username]}:#{@options[:password]}"
            auth = Base64.strict_encode64(creds)
            body = data
            uri = URI.parse(@api_url)
            http = Net::HTTP.new(uri.host, uri.port)
            http.use_ssl = true
            url = "/xml/"
            request = Net::HTTP::Post.new(url)
            request.add_field("Content-Type", 'text/xml; charset=utf-8')
            request.add_field("Content-Length", body.bytesize)    
            request.add_field("Accept", "text/xml")    
            request.add_field('Accept-Encoding', "gzip")
            request.add_field("Authorization", "Basic #{auth}")
            request.add_field('User-Agent', "Goalmouth; 0.1")
            request.add_field("Host", "webservices.securetrading.net")
            request.add_field("Connection", "close")
            request.body = body
            http.request(request)
        end

    end
  end
end