# Path: pystil/context.py
# class url(object):
#     def __init__(self, url):
#         self.url = url
# 
#     def __call__(self, cls):
#         pystil.add_handlers(
#             r'.*$',
#             (unnamed_url(self.url, cls, name=cls.__name__),)
#         )
#         return cls
# 
# MESSAGE_QUEUE = Queue()
# 
# @property
# def log(self):
#     return log
# 
# class Hdr(RequestHandler):
#     @property
#     def db(self):
#         return self.application.db
# 
#     @property
#     def log(self):
#         return log
# 
#     def prepare(self):
#         if not self.get_secure_cookie('_pystil_site'):
#             self.log.info('Setting secure cookie')
#             self.set_secure_cookie('_pystil_site', 'local|' + str(uuid4()))
# 
#     def on_finish(self):
#         self.db.rollback()
# 
# Path: pystil/db.py
# class CriterionView(Base):
#     __tablename__ = 'criterion_view'
# 
#     id = integer(pkey=True)
#     uuid = string()
#     browser_name = string()
#     hash = string()
#     host = string()
#     browser_version = string()
#     client_tz_offset = integer()
#     date = datetime()
#     last_visit = datetime()
#     ip = string()
#     language = string()
#     page = string()
#     platform = string()
#     query = string()
#     referrer = string()
#     pretty_referrer = string()
#     referrer_domain = string()
#     site = string()
#     size = string()
#     time = Column(Interval)
#     country = string()
#     country_code = string()
#     city = string()
#     lat = decimal()
#     lng = decimal()
#     asn = string()
# 
#     browser_name_version = string()
#     day = date_column()
#     hour = integer()
#     subdomain = string()
#     domain = string()
# 
# Path: pystil/utils.py
# def visit_to_table_line(visit):
#     html = '<tr data-visit-uuid="%s">' % visit.uuid
#     for key in [
#             'date', 'host', 'ip', 'country',
#             'city', 'page', 'referrer']:
#         val = getattr(visit, key)
#         title = None
#         if val:
#             if key == 'date':
#                 val = val.strftime('%Y-%m-%d %H:%M:%S')
#             if key == 'referrer':
#                 title = val
#                 val = parse_referrer(val, True, True)
#         else:
#             val = ''
#         title = title or val
#         html += '<td title="%s">' % title
#         html += '<a href="/criterion/%s/%s">' % (key, val)
#         html += val
#         html += '</>'
#         html += '</td>'
#     html += ('<td>'
#              '<a href="/visit/%d"><i class="icon-search"></i></a>'
#              '</td>' % visit.id)
#     html += '</tr>'
#     return html


from tornado.websocket import WebSocketHandler
from pystil.context import url, MESSAGE_QUEUE, log, Hdr
from pystil.db import CriterionView as Visit
from tornado.options import options
from tornado.ioloop import IOLoop
from psycopg2.extensions import POLL_OK, POLL_READ, POLL_WRITE
from sqlalchemy.sql.compiler import SQLCompiler
from sqlalchemy.sql.expression import between
from pystil.utils import visit_to_table_line
from sqlalchemy import func
from datetime import datetime, timedelta
from functools import partial
import psycopg2
import momoko
        else:
            log.warn('Last visits websocket open without secure cookie')
            self.close()

    def on_message(self, message):
        if message == '/count':
            self.write_message(
                'INFO|There are %d clients' % len(LastVisitsWebSocket.waiters))
        elif message == '/queue_count':
            self.write_message(
                'INFO|There are %d waiting messages' % MESSAGE_QUEUE.qsize())
        elif message == '/site':
            self.write_message(
                'INFO|You are on %s' % self.site)

    def on_close(self):
        if self in LastVisitsWebSocket.waiters:
            LastVisitsWebSocket.waiters.remove(self)


def broadcast(message):
    for client in set(LastVisitsWebSocket.waiters):
        try:
            client.write_message(message)
        except:
            client.log.warn('Error broadcasting to %r' % client, exc_info=True)
            LastVisitsWebSocket.waiters.remove(client)
            client.close()



# Path: pystil/context.py
# class url(object):
#     def __init__(self, url):
#         self.url = url
# 
#     def __call__(self, cls):
#         pystil.add_handlers(
#             r'.*$',
#             (unnamed_url(self.url, cls, name=cls.__name__),)
#         )
#         return cls
# 
# MESSAGE_QUEUE = Queue()
# 
# @property
# def log(self):
#     return log
# 
# class Hdr(RequestHandler):
#     @property
#     def db(self):
#         return self.application.db
# 
#     @property
#     def log(self):
#         return log
# 
#     def prepare(self):
#         if not self.get_secure_cookie('_pystil_site'):
#             self.log.info('Setting secure cookie')
#             self.set_secure_cookie('_pystil_site', 'local|' + str(uuid4()))
# 
#     def on_finish(self):
#         self.db.rollback()
# 
# Path: pystil/db.py
# class CriterionView(Base):
#     __tablename__ = 'criterion_view'
# 
#     id = integer(pkey=True)
#     uuid = string()
#     browser_name = string()
#     hash = string()
#     host = string()
#     browser_version = string()
#     client_tz_offset = integer()
#     date = datetime()
#     last_visit = datetime()
#     ip = string()
#     language = string()
#     page = string()
#     platform = string()
#     query = string()
#     referrer = string()
#     pretty_referrer = string()
#     referrer_domain = string()
#     site = string()
#     size = string()
#     time = Column(Interval)
#     country = string()
#     country_code = string()
#     city = string()
#     lat = decimal()
#     lng = decimal()
#     asn = string()
# 
#     browser_name_version = string()
#     day = date_column()
#     hour = integer()
#     subdomain = string()
#     domain = string()
# 
# Path: pystil/utils.py
# def visit_to_table_line(visit):
#     html = '<tr data-visit-uuid="%s">' % visit.uuid
#     for key in [
#             'date', 'host', 'ip', 'country',
#             'city', 'page', 'referrer']:
#         val = getattr(visit, key)
#         title = None
#         if val:
#             if key == 'date':
#                 val = val.strftime('%Y-%m-%d %H:%M:%S')
#             if key == 'referrer':
#                 title = val
#                 val = parse_referrer(val, True, True)
#         else:
#             val = ''
#         title = title or val
#         html += '<td title="%s">' % title
#         html += '<a href="/criterion/%s/%s">' % (key, val)
#         html += val
#         html += '</>'
#         html += '</td>'
#     html += ('<td>'
#              '<a href="/visit/%d"><i class="icon-search"></i></a>'
#              '</td>' % visit.id)
#     html += '</tr>'
#     return html


# Path: pystil/websocket.py
from tornado.websocket import WebSocketHandler
from pystil.context import url, MESSAGE_QUEUE, log, Hdr
from pystil.db import CriterionView as Visit
from tornado.options import options
from tornado.ioloop import IOLoop
from psycopg2.extensions import POLL_OK, POLL_READ, POLL_WRITE
from sqlalchemy.sql.compiler import SQLCompiler
from sqlalchemy.sql.expression import between
from pystil.utils import visit_to_table_line
from sqlalchemy import func
from datetime import datetime, timedelta
from functools import partial
import psycopg2
import momoko

        else:
            log.warn('Last visits websocket open without secure cookie')
            self.close()

    def on_message(self, message):
        if message == '/count':
            self.write_message(
                'INFO|There are %d clients' % len(LastVisitsWebSocket.waiters))
        elif message == '/queue_count':
            self.write_message(
                'INFO|There are %d waiting messages' % MESSAGE_QUEUE.qsize())
        elif message == '/site':
            self.write_message(
                'INFO|You are on %s' % self.site)

    def on_close(self):
        if self in LastVisitsWebSocket.waiters:
            LastVisitsWebSocket.waiters.remove(self)


def broadcast(message):
    for client in set(LastVisitsWebSocket.waiters):
        try:
            client.write_message(message)
        except:
            client.log.warn('Error broadcasting to %r' % client, exc_info=True)
            LastVisitsWebSocket.waiters.remove(client)
            client.close()



@url(r'/query')