import datetime
import logging

import gevent
import geventwebsocket

from .ext_json import json

log = logging.getLogger(__name__)


class Connection(object):
    """ Represents a browser connection"""

    def __init__(self, username, conn_id):
        self.username = username  # hold user id/name of connection
        self.last_active = datetime.datetime.utcnow()
        self.socket = None
        self.queue = None
        self.id = conn_id
        gevent.spawn_later(5, self.heartbeat)

    def __repr__(self):
        return '<Connection: id:%s, owner:%s>' % (self.id, self.username)

    def add_message(self, message=None):
        """ Sends the message to the client connection """
        # handle websockets
        if self.socket:
            try:
                # payload needs to be converted to JSON now as it gets
                # piped to client
                self.socket.ws.send(json.dumps([message] if message else []))
                self.last_active = datetime.datetime.utcnow()
            except geventwebsocket.exceptions.WebSocketError:
                self.mark_for_gc()
        elif self.queue:
            # handle long polling
            # payload will be converted to JSON in WSGI response
            self.queue.put([message] if message else [])

    def mark_for_gc(self):
        # set last active time for connection 1 hour in past for GC
        self.last_active -= datetime.timedelta(days=60)

    def heartbeat(self):
        if self.socket or self.queue:
            try:
                self.add_message()
                gevent.spawn_later(5, self.heartbeat)
            except Exception:
                self.mark_for_gc()
                if self.socket:
                    self.socket.ws.close()

@@ -1,23 +1,36 @@
 import 
+logging%0Afrom 
 datetime
 %0Aimport 
@@ -25,23 +25,35 @@
 time
-%0A
+ 
 import 
-logging
+datetime, timedelta
 %0A%0Aim
@@ -88,16 +88,37 @@
 socket%0A%0A
+import channelstream%0A
 from .ex
@@ -377,33 +377,24 @@
 st_active = 
-datetime.
 datetime.utc
@@ -996,53 +996,139 @@
     
-self.last_active = datetime.datetime.utc
+now = datetime.utcnow()%0A                self.last_active = now%0A                channelstream.USERS%5Bself.username%5D.last_active = 
 now
-()
 %0A   
@@ -1498,16 +1498,16 @@
  for GC%0A
+
         
@@ -1526,25 +1526,16 @@
 tive -= 
-datetime.
 timedelt

mark user last active as well when a message is piped