module Softwear
  module Library
    class LightServerSocket
      def initialize(host, port)
        $zmq_context ||= ZMQ::Context.new
        @req = $zmq_context.connect(:REQ, "tcp://#{host}:#{port}")
      end

      def send(message)
        @req.send(message)
      end

      def recv
        @req.recv
      end

      def destroy
        @req.try(:destroy)
        @req = nil
      end
    end

    class LightServerWebSocket
      def initialize(host)
        @host = host
        connect!
      end

      def connect!
        @ws = Faye::WebSocket::Client.new(@host)
        @recved_messages = Queue.new

        @ws.on :open do |event|
          puts "OPENED!"
        end

        @ws.on :message do |event|
          puts "CLIENT RECV! #{message}"
          @recved_messages.push event.data
        end

        @ws.on :close do |event|
          puts "CLOSED!"
          connect!
        end
      end

      def send(message)
        @ws.send message
      end

      def recv
        Timeout::timeout(5) do
          while @recved_messages.empty?
            sleep 0.01
          end
        end
        @recved_messages.pop
      end

      def destroy
        @ws.try(:close, 1000)
        @ws = nil
      end
    end
  end
end
