<commit_before>require 'progenitor/messages'

module Progenitor
  module PlayerHandler
    attr_accessor :parent
    def unbind
      parent.disconnect
    end
  end

  class Player
    attr_accessor :spalla_id, :host, :port

    def initialize(id,  host, port)
      @spalla_id = id
      @host = host
      @port = port
    end

    def hear(event_name, event_value)
      message = Messages.build_event(@spalla_id, event_name, event_value)
      send_message(message)
    end

    def new_connection(message)
      EventMachine::connect(@host, @port, PlayerHandler) do |connection|
        @connection = connection
        @connection.parent = self
        send_data(message)
      end
    end

    def disconnect
      @connection = nil
    end

    def terminate
      @connection.close_connection_after_writing
    end

    def send_message(message)
      #TODO:   multiple sends before a connect
      if @connection
        send_data(message)
      else
        new_connection(message)
      end
    end

    def send_data(data)
      @connection.send_data("%06d" % data.length)
      @connection.send_data(data)
    end

  end
end<commit_msg>handle multiple sends before connection established<commit_after>require 'progenitor/messages'

module Progenitor
  module PlayerHandler
    attr_accessor :parent
    def unbind
      parent.disconnect
    end
  end

  class Player
    attr_accessor :spalla_id, :host, :port

    def initialize(id,  host, port)
      @spalla_id = id
      @host = host
      @port = port
      @backlog = []
    end

    def hear(event_name, event_value)
      message = Messages.build_event(@spalla_id, event_name, event_value)
      send_message(message)
    end

    def new_connection
      EventMachine::connect(@host, @port, PlayerHandler) do |connection|
        @connection = connection
        @connection.parent = self
        @backlog.each { |message| send_data(message) }
        @backlog.clear
      end
    end

    def disconnect
      terminate
      @connection = nil
    end

    def terminate
      @connection.close_connection_after_writing if @connection
    end

    def send_message(message)
      if @connection
        send_data(message)
      else
        @backlog << message
        new_connection if @backlog.size == 1
      end
    end

    def send_data(data)
      @connection.send_data("%06d" % data.length)
      @connection.send_data(data)
    end

  end
end
{'fraction_non_alphanumeric': 0.07334157395962093, 'fraction_numerical': 0.0020601565718994645, 'mean_word_length': 2.4735336194563664, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1171709', 'n_tokens_mistral': 741, 'n_tokens_neox': 715, 'n_words': 180}