require 'singleton'

#Acts as wrapper for the gateway
#
module EhXero
  class Gateway
    attr_accessor :context, :gateway

    def initialize(api_v2: false)
      @api_v2 = api_v2
      @gateway = init_gateway
    end

    def access!(context)
      @context = context.with_indifferent_access
      gateway.authorize_from_access(@context[:xero_access_token], @context[:xero_access_secret])
    end

    def request_token_with_callback
      gateway.request_token(oauth_callback: EhXero.config.xero_callback)
    end

    private

    def method_missing(method_name, *arguments)
      gateway.send(method_name, *arguments)
    end

    def init_gateway
      gateway_opts = [
        EhXero.config.xero_consumer_key,
        EhXero.config.xero_consumer_secret,
        "#{Rails.root}/config/privatekey.pem"
      ]

      custom_opts = {}
      if !@api_v2
        custom_opts[:xero_url] = "https://api.xero.com/payroll.xro/1.0"
      end

      custom_opts[:rate_limit_sleep] = 61
      custom_opts[:rate_limit_max_attempts] = 1
      custom_opts[:logger] = ::Logger.new(STDOUT) if EhXero.config.debug

      gateway_opts << custom_opts

      Xeroizer::PartnerApplication.new(*gateway_opts)
    end
  end
end
