# frozen-string-literal: true

require 'andpush'
require 'active_support/core_ext/hash/transform_values'

module Pushing
  module Adapters
    class AndpushAdapter
      def initialize(fcm_settings)
        @server_key = fcm_settings.server_key
      end

      def push!(notification)
        FcmResponse.new(self.class.client(@server_key).push(notification.payload))
      rescue => e
        raise Pushing::FcmDeliveryError.new("Error while trying to send push notification: #{e.message}", FcmResponse.new(e.response))
      end

      @@semaphore = Mutex.new

      def self.client(server_key)
        defined?(@client) ? @client : @@semaphore.synchronize { @client ||= Andpush.build(server_key) }
      end

      class FcmResponse < SimpleDelegator
        def code
          __getobj__.code.to_i
        end

        def headers
          __getobj__.headers.transform_values {|value| value.join(", ") }
        end
      end

      private_constant :FcmResponse
    end
  end
end

# frozen-string-literal: true

require 'andpush'
require 'active_support/core_ext/hash/transform_values'

module Pushing
  module Adapters
    class AndpushAdapter
      def initialize(fcm_settings)
        @server_key = fcm_settings.server_key
      end

      def push!(notification)
        FcmResponse.new(self.class.client(@server_key).push(notification.payload))
      rescue => e
        response = e.respond_to?(:response) ? FcmResponse.new(e.response) : nil

        raise Pushing::FcmDeliveryError.new("Error while trying to send push notification: #{e.message}", response)
      end

      @@semaphore = Mutex.new

      def self.client(server_key)
        defined?(@client) ? @client : @@semaphore.synchronize { @client ||= Andpush.build(server_key) }
      end

      class FcmResponse < SimpleDelegator
        def code
          __getobj__.code.to_i
        end

        def headers
          __getobj__.headers.transform_values {|value| value.join(", ") }
        end
      end

      private_constant :FcmResponse
    end
  end
end

Make sure to not create a response wrapepr object if not present
Make sure to not create a response wrapepr object if not present

If the exception is a conneciton error (e.g. Timeout, SSL error), the response object ends up being nil and it doesn't make sense to wrap a nil object. In case of network/connection error, just skip wrapping it so we can save work and things will be less buggy.
