http      = require 'http'
zmq       = require 'zmq'
socketio  = require 'socket.io'
static    = require 'node-static'
nlogger   = require 'nlogger'
util      = require 'util'

log = nlogger.logger module

inPort = 5555
outPort = 5556
httpPort = 8080
staticPath = '.'

# To hold socket.io sockets
connectedSockets = {}

inSocket = zmq.createSocket 'push'
inSocket.bind "tcp://127.0.0.1:#{inPort}", (e) ->

outSocket = zmq.createSocket 'pull'
outSocket.bind "tcp://127.0.0.1:#{outPort}", (e) ->
  outSocket.on 'message', (m) ->
    title = m.toString('utf-8')
    log.debug('title: {}', title)
    for id of connectedSockets
      connectedSockets[id].send(title)

titles =
  '/1': 'Alfa Romeo Alfetta'
  '/2': 'Alfa Romeo "Nuova" Giulietta'
  '/3': 'Alfa Romeo 33'
  '/4': 'Alfa Romeo 75'
  '/5': 'Alfa Romeo 164'
  '/6': 'Alfa Romeo 155'
  '/7': 'Alfa Romeo 156'
  '/8': 'Alfa Romeo 166'
  '/9': 'Alfa Romeo 159'

# Static serve init

file = new static.Server staticPath
app = http.createServer (request, response) ->
  request.addListener 'end', ->
    if request.url of titles
      t = titles[request.url]
      response.writeHead 200, 'Content-Type': 'text/html'
      response.end "<html><head><title>#{t}</title></head><body>#{t}</body></html>"
    else
      file.serve(request, response)
app.listen httpPort

# Socket.IO init
io = socketio.listen app
io.configure ->
  io.set 'transports', ['websocket', 'flashsocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']
  io.set 'browser client', true
  io.set 'log level', 1
  io.set 'heartbeats', true

io.sockets.on 'connection', (s) ->
  log.debug 'Connect: {} {}', s.id, s.manager.transports[s.id].name
  connectedSockets[s.id] = s

  s.on 'message', (url) ->
    log.debug 'Got url: {}', url
    inSocket.send url

  s.on 'disconnect', ->
    delete connectedSockets[s.id]

