module JamRuby
  class BaseManager

    attr_accessor :pg_conn

    @@log = Logging.logger[BaseManager]

    # this is not working as expected
    #@@in_websocket_gateway = Rails.env != 'test' && !Object.const_defined?(:UserManager)

    @@in_websocket_gateway = false

    def initialize(options={})
      @log = Logging.logger[self]
      @pg_conn = options[:conn]

      unless PG.threadsafe?
        raise Exception, "a non-threadsafe build of libpq is present."
      end
    end

       # Creates a connection manager, and associates the connection created by active_record with ourselves
    def self.active_record_transaction

      manager = self.new
      ActiveRecord::Base.connection_pool.with_connection do |connection|
        # create a transaction, and pass the current connection to ConnectionManager.
        # this lets the entire operation work with the same transaction,
        # across Rails ActiveRecord and the pg-gem based code in ConnectionManager.
        conn = connection.instance_variable_get("@connection")
        manager.pg_conn = conn

        if @@in_websocket_gateway
          # it only necessary to catch exceptions in websocket-gateway, which has only one AR connection and does not clean it up like a Rails context does
          begin
            connection.transaction do
              yield manager, conn
            end
          rescue Exception => e
            ActiveRecord::Base.connection.execute('ROLLBACK')
          end
        else
          connection.transaction do
            yield manager, conn
          end
        end
      end
    end
  end
end