# Path: automlk/monitor.py
# def get_heart_beeps(module):
#     """
#     returns last heart beeps of the controller and workers
# 
#     :param module: controller / worker
#     :return: list of status or empty list (eg. if environment not set)
#     """
#     # returns values of heart beeps
#     try:
#         # get list and values
#         l = smembers_key_store('monitor:%s' % module)
#         l_hb = [get_key_store('monitor:%s:%s' % (module, id)) for id in l]
# 
#         # filter on heart beeps < 12h
#         return [h for h in l_hb if
#                 (datetime.datetime.now() - datetime.datetime(**h['time'])) < datetime.timedelta(hours=12)]
#     except:
#         return []
# 
# Path: automlk/context.py
# def get_config():
#     """
# 
#     retrieves configuration parameters
#     :return: config dict
#     """
#     if os.path.exists('../config.json'):
#         with open('../config.json', 'r') as f:
#             config = eval("".join(f.readlines()))
#             # upward compatibility
#             if 'bootstrap' not in config.keys():
#                 config['bootstrap'] = ''
#             if 'graph_theme' not in config.keys():
#                 config['graph_theme'] = 'dark'
#             if 'doc_theme' not in config.keys():
#                 config['doc_theme'] = 'default'
#             return config
#     raise EnvironmentError('configuration file %s not found' % '../config.json')
# 
# def set_config(data, theme, bootstrap, graph_theme, store, store_url):
#     """
#     set config data
# 
#     :param data: path to data storage
#     :param theme: theme for user interface
#     :param bootstrap: specific url for a bootstrap
#     :param graph_theme: style for graphs (dark / white)
#     :param store: store mode (redis / file)
#     :param store_url: url if redis mode
#     :return:
#     """
#     # check data
#     if not os.path.exists(data):
#         raise EnvironmentError('data folder %s do not exist' % data)
# 
#     if store == 'redis':
#         # check connection to redis
#         try:
#             import redis
#             rds = redis.Redis(host=store_url)
#             rds.exists('test')
#         except:
#             raise EnvironmentError('could not connect to redis')
#         set_use_redis(True)
#     else:
#         store_folder = data + '/store'
#         if not os.path.exists(store_folder):
#             os.makedirs(store_folder)
#         set_use_redis(False)
# 
#     # then save config
#     config = {'data': data, 'theme': theme, 'bootstrap': bootstrap, 'graph_theme': graph_theme, 'store': store,
#               'store_url': store_url}
#     with open('../config.json', 'w') as f:
#         f.write(json.dumps(config) + '\n')


from app import app
from flask import render_template, request, flash
from .form import *
from automlk.monitor import get_heart_beeps
from automlk.context import get_config, set_config


@app.route('/monitor', methods=['GET'])
def monitor():
    # monitor workers
    return render_template('monitor.html', controller=get_heart_beeps('controller'),
                           grapher=get_heart_beeps('grapher'), worker_text=get_heart_beeps('worker_text'),
                           workers=get_heart_beeps('worker'), config=get_config())


@app.route('/config', methods=['GET', 'POST'])
def config():
    # view/edit configuration
    form = ConfigForm()
    if request.method == 'POST':
        if form.validate():
            try:

# Path: automlk/monitor.py
# def get_heart_beeps(module):
#     """
#     returns last heart beeps of the controller and workers
# 
#     :param module: controller / worker
#     :return: list of status or empty list (eg. if environment not set)
#     """
#     # returns values of heart beeps
#     try:
#         # get list and values
#         l = smembers_key_store('monitor:%s' % module)
#         l_hb = [get_key_store('monitor:%s:%s' % (module, id)) for id in l]
# 
#         # filter on heart beeps < 12h
#         return [h for h in l_hb if
#                 (datetime.datetime.now() - datetime.datetime(**h['time'])) < datetime.timedelta(hours=12)]
#     except:
#         return []
# 
# Path: automlk/context.py
# def get_config():
#     """
# 
#     retrieves configuration parameters
#     :return: config dict
#     """
#     if os.path.exists('../config.json'):
#         with open('../config.json', 'r') as f:
#             config = eval("".join(f.readlines()))
#             # upward compatibility
#             if 'bootstrap' not in config.keys():
#                 config['bootstrap'] = ''
#             if 'graph_theme' not in config.keys():
#                 config['graph_theme'] = 'dark'
#             if 'doc_theme' not in config.keys():
#                 config['doc_theme'] = 'default'
#             return config
#     raise EnvironmentError('configuration file %s not found' % '../config.json')
# 
# def set_config(data, theme, bootstrap, graph_theme, store, store_url):
#     """
#     set config data
# 
#     :param data: path to data storage
#     :param theme: theme for user interface
#     :param bootstrap: specific url for a bootstrap
#     :param graph_theme: style for graphs (dark / white)
#     :param store: store mode (redis / file)
#     :param store_url: url if redis mode
#     :return:
#     """
#     # check data
#     if not os.path.exists(data):
#         raise EnvironmentError('data folder %s do not exist' % data)
# 
#     if store == 'redis':
#         # check connection to redis
#         try:
#             import redis
#             rds = redis.Redis(host=store_url)
#             rds.exists('test')
#         except:
#             raise EnvironmentError('could not connect to redis')
#         set_use_redis(True)
#     else:
#         store_folder = data + '/store'
#         if not os.path.exists(store_folder):
#             os.makedirs(store_folder)
#         set_use_redis(False)
# 
#     # then save config
#     config = {'data': data, 'theme': theme, 'bootstrap': bootstrap, 'graph_theme': graph_theme, 'store': store,
#               'store_url': store_url}
#     with open('../config.json', 'w') as f:
#         f.write(json.dumps(config) + '\n')


# Path: web/app/views_admin.py
from app import app
from flask import render_template, request, flash
from .form import *
from automlk.monitor import get_heart_beeps
from automlk.context import get_config, set_config



@app.route('/monitor', methods=['GET'])
def monitor():
    # monitor workers
    return render_template('monitor.html', controller=get_heart_beeps('controller'),
                           grapher=get_heart_beeps('grapher'), worker_text=get_heart_beeps('worker_text'),
                           workers=get_heart_beeps('worker'), config=get_config())


@app.route('/config', methods=['GET', 'POST'])
def config():
    # view/edit configuration
    form = ConfigForm()
    if request.method == 'POST':
        if form.validate():
            try:

                set_config(data=form.data.data,