# Path: tilde/berlinium/impl.py
# class GUIProviderMockup:
#     pass
# 
# class Client:
#     def __init__(self):
#         self.usettings = {}
#         self.authorized = False
#         self.db = None
# 
# Path: tilde/core/settings.py
# DB_SCHEMA_VERSION = '5.20'
# SETTINGS_FILE = 'settings.json'
# DEFAULT_SQLITE_DB = 'default.db'
# BASE_DIR = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
# ROOT_DIR = os.path.normpath(BASE_DIR + '/../')
# DATA_DIR = os.path.join(ROOT_DIR, 'data')
# EXAMPLE_DIR = os.path.join(ROOT_DIR, '../tests/data')
# INIT_DATA = os.path.join(DATA_DIR, 'sql/init-data.sql')
# TEST_DBS_FILE = os.path.join(DATA_DIR, 'test_dbs.txt')
# TEST_DBS_REF_FILE = os.path.join(DATA_DIR, 'test_dbs_ref.txt')
# SETTINGS_PATH = DATA_DIR + os.sep + SETTINGS_FILE
# GUI_URL_TPL = 'http://tilde-lab.github.io/berlinium/?http://127.0.0.1:%s' # ?https://db.tilde.pro
# DEFAULT_SETUP = {
# 
#     # General part
#     'debug_regime': False, # TODO
#     'log_dir': os.path.join(DATA_DIR, "logs"), # TODO
#     'skip_unfinished': False,
#     'skip_notenergy': False,
#     'skip_if_path': [],
# 
#     # DB part
#     'db': {
#         'default_sqlite_db': DEFAULT_SQLITE_DB,
#         'engine': 'sqlite', # if sqlite is chosen: further info is not used
#         'host': 'localhost',
#         'port': 5432,
#         'user': 'postgres',
#         'password': '',
#         'dbname': 'tilde'
#     },
# 
#     # Server part
#     'webport': 8070,
#     'title': "Tilde GUI"
# }
# def virtualize_path(item):
# def connect_url(settings, named=None):
# def connect_database(settings, named=None, no_pooling=False, default_actions=True, scoped=False):
# def write_settings(settings):
# def get_hierarchy(settings):


import logging
import ujson as json
from tornado import ioloop
from sockjs.tornado import SockJSConnection
from tilde.berlinium.impl import GUIProviderMockup, Client
from tilde.core.settings import settings, connect_database
    Clients = {}
    GUIProvider = GUIProviderMockup

    def on_open(self, info):
        self.Clients[ getattr(self.session, 'session_id', self.session.__hash__()) ] = Client()
        logging.info("Server connected %s-th client" % len(self.Clients))

    def on_message(self, message):
        logging.debug("Server got: %s" % message)
        try:
            message = json.loads(message)
            message.get('act')
        except: return self.send(json.dumps({'act':'login', 'error':'Not a valid JSON!'}))

        frame = {
            'client_id': getattr(self.session, 'session_id', self.session.__hash__()),
            'act': message.get('act', 'unknown'),
            'req': message.get('req', ''),
            'error': '',
            'result': ''
        }

        # security check: a client must be authorized
        if not self.Clients[frame['client_id']].authorized and frame['act'] != 'login': return self.close()

        if not hasattr(self.GUIProvider, frame['act']):
            frame['error'] = 'No server handler for action: %s' % frame['act']
            return self.respond(frame)

        if not Connection.Clients[frame['client_id']].db:

# Path: tilde/berlinium/impl.py
# class GUIProviderMockup:
#     pass
# 
# class Client:
#     def __init__(self):
#         self.usettings = {}
#         self.authorized = False
#         self.db = None
# 
# Path: tilde/core/settings.py
# DB_SCHEMA_VERSION = '5.20'
# SETTINGS_FILE = 'settings.json'
# DEFAULT_SQLITE_DB = 'default.db'
# BASE_DIR = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
# ROOT_DIR = os.path.normpath(BASE_DIR + '/../')
# DATA_DIR = os.path.join(ROOT_DIR, 'data')
# EXAMPLE_DIR = os.path.join(ROOT_DIR, '../tests/data')
# INIT_DATA = os.path.join(DATA_DIR, 'sql/init-data.sql')
# TEST_DBS_FILE = os.path.join(DATA_DIR, 'test_dbs.txt')
# TEST_DBS_REF_FILE = os.path.join(DATA_DIR, 'test_dbs_ref.txt')
# SETTINGS_PATH = DATA_DIR + os.sep + SETTINGS_FILE
# GUI_URL_TPL = 'http://tilde-lab.github.io/berlinium/?http://127.0.0.1:%s' # ?https://db.tilde.pro
# DEFAULT_SETUP = {
# 
#     # General part
#     'debug_regime': False, # TODO
#     'log_dir': os.path.join(DATA_DIR, "logs"), # TODO
#     'skip_unfinished': False,
#     'skip_notenergy': False,
#     'skip_if_path': [],
# 
#     # DB part
#     'db': {
#         'default_sqlite_db': DEFAULT_SQLITE_DB,
#         'engine': 'sqlite', # if sqlite is chosen: further info is not used
#         'host': 'localhost',
#         'port': 5432,
#         'user': 'postgres',
#         'password': '',
#         'dbname': 'tilde'
#     },
# 
#     # Server part
#     'webport': 8070,
#     'title': "Tilde GUI"
# }
# def virtualize_path(item):
# def connect_url(settings, named=None):
# def connect_database(settings, named=None, no_pooling=False, default_actions=True, scoped=False):
# def write_settings(settings):
# def get_hierarchy(settings):


# Path: tilde/berlinium/block_impl.py
import logging
import ujson as json
from tornado import ioloop
from sockjs.tornado import SockJSConnection
from tilde.berlinium.impl import GUIProviderMockup, Client
from tilde.core.settings import settings, connect_database

    Clients = {}
    GUIProvider = GUIProviderMockup

    def on_open(self, info):
        self.Clients[ getattr(self.session, 'session_id', self.session.__hash__()) ] = Client()
        logging.info("Server connected %s-th client" % len(self.Clients))

    def on_message(self, message):
        logging.debug("Server got: %s" % message)
        try:
            message = json.loads(message)
            message.get('act')
        except: return self.send(json.dumps({'act':'login', 'error':'Not a valid JSON!'}))

        frame = {
            'client_id': getattr(self.session, 'session_id', self.session.__hash__()),
            'act': message.get('act', 'unknown'),
            'req': message.get('req', ''),
            'error': '',
            'result': ''
        }

        # security check: a client must be authorized
        if not self.Clients[frame['client_id']].authorized and frame['act'] != 'login': return self.close()

        if not hasattr(self.GUIProvider, frame['act']):
            frame['error'] = 'No server handler for action: %s' % frame['act']
            return self.respond(frame)

        if not Connection.Clients[frame['client_id']].db:

            Connection.Clients[frame['client_id']].db = connect_database(settings, default_actions=False, no_pooling=True)