module Flamingo
  class DispatchEvent

    @parser = Yajl::Parser.new(:symbolize_keys => true)

    class << self
      
      def queue
        Flamingo.dispatch_queue
      end

      #
      # TODO Track stats including: tweets per second and last tweet time
      # TODO Provide some first-level check for repeated status ids
      # TODO Consider subscribers for receiving particular terms - do the heavy
      #      lifting of parsing tweets and delivering them to particular subscribers
      # TODO Consider window of tweets (approx 3 seconds) and sort before
      #      dispatching to improve in-order delivery (helps with "k-sorted")
      #
      def perform(event_json)
        type, event = typed_event(parse(event_json))
        Subscription.all.each do |sub|
          Resque::Job.create(sub.name, "HandleFlamingoEvent", type, event)
          Flamingo.logger.debug "Put job on subscription queue #{sub.name}\n#{event_json}"
        end
      end

      def parse(json)
        @parser.parse(json)
      end

      def typed_event(event)
        if event[:delete]
          [:delete, event[:delete]]
        elsif event[:link]
          [:link,   event[:link]]
        else
          [:tweet,  event]
        end
      end

    end
  end
end

module Flamingo
  class DispatchEvent

    @parser = Yajl::Parser.new(:symbolize_keys => true)

    class << self
      
      def queue
        Flamingo.dispatch_queue
      end
      
      def meta
        Flamingo.meta
      end

      #
      # TODO Track stats including: tweets per second and last tweet time
      # TODO Provide some first-level check for repeated status ids
      # TODO Consider subscribers for receiving particular terms - do the heavy
      #      lifting of parsing tweets and delivering them to particular subscribers
      # TODO Consider window of tweets (approx 3 seconds) and sort before
      #      dispatching to improve in-order delivery (helps with "k-sorted")
      #
      def perform(event_json)
        meta.incr("events:all_count")
        meta.set("events:last_time",Time.now.utc.to_i)
        type, event = typed_event(parse(event_json))
        meta.incr("events:#{type}_count")
        Subscription.all.each do |sub|
          Resque::Job.create(sub.name, "HandleFlamingoEvent", type, event)
          Flamingo.logger.debug "Put job on subscription queue #{sub.name}\n#{event_json}"
        end
      end

      def parse(json)
        @parser.parse(json)
      end

      def typed_event(event)
        if event[:delete]
          [:delete, event[:delete]]
        elsif event[:link]
          [:link,   event[:link]]
        else
          [:tweet,  event]
        end
      end

    end
  end
end

Set some Meta info for events as they're processed by the dispatcher.
Set some Meta info for events as they're processed by the dispatcher.
