# Path: prosoar/userconfig.py
# def get_uid_from_cookie():
#     if 'uid' not in request.cookies:
#         return create_uid()
# 
#     p = re.compile('([0-9a-z]*)\.([0-9a-z]*)')
#     m = p.match(request.cookies['uid'].lower())
#     if not m:
#         return create_uid()
# 
#     uid = {'uid': m.group(1), 'key': m.group(2)}
#     path = os.path.join(
#         current_app.config['USERS_FOLDER'], uid['uid'], 'key_' + uid['key'])
#     if not os.path.exists(path):
#         return create_uid()
# 
#     return uid
# 
# def get_user_config_as_json(
#         uid, lastvisit=True, turnpointFiles=True, taskFiles=True,
#         encoded=True):
# 
#     userconfig = read_user_config(uid)
# 
#     json_string = {}
# 
#     json_string['uid'] = uid['uid'] + "." + uid['key']
# 
#     if turnpointFiles:
#         json_string['turnpointFiles'] = {}
# 
#         for key, value in enumerate(userconfig['tp_files']):
#             json_string['turnpointFiles'][key] = {
#                 'filename': value['name'],
#                 'id': (key + 1),
#                 'display': value['display']
#             }
# 
#     if taskFiles:
#         json_string['taskFiles'] = {}
# 
#         for key, value in enumerate(userconfig['task_files']):
#             json_string['taskFiles'][key] = {
#                 'name': value['name'],
#                 'distance': value['distance'],
#                 'type': value['type'],
#                 'turnpoints': value['turnpoints'],
#                 'date': value['date']
#             }
# 
#     if lastvisit:
#         json_string['lastvisit'] = userconfig['lastvisit']
# 
#     if encoded:
#         return json.dumps(json_string, indent=1)
# 
#     return json_string


from flask import Blueprint, request, jsonify
from geoip import geolite2
from prosoar.userconfig import get_uid_from_cookie, get_user_config_as_json
bp = Blueprint('settings', __name__)


@bp.route('/initial.js')
def initial_js():
    return load(type='js')


@bp.route('/load')
def load(type='json'):
    uid = get_uid_from_cookie()

    type = request.values.get('as', type)

    if type == 'js':
        match = geolite2.lookup(request.remote_addr)

        settings = \
            'var initialSettings = ' + get_user_config_as_json(uid) + ';'

        if match and match.location:
            location = 'var initialLocation = {lon: ' + \
                str(match.location[1]) + ', lat: ' + \
                str(match.location[0]) + '};'
        else:
            location = 'var initialLocation = {lon: 10, lat: 50};'

        return settings + location

    elif type == 'json':

# Path: prosoar/userconfig.py
# def get_uid_from_cookie():
#     if 'uid' not in request.cookies:
#         return create_uid()
# 
#     p = re.compile('([0-9a-z]*)\.([0-9a-z]*)')
#     m = p.match(request.cookies['uid'].lower())
#     if not m:
#         return create_uid()
# 
#     uid = {'uid': m.group(1), 'key': m.group(2)}
#     path = os.path.join(
#         current_app.config['USERS_FOLDER'], uid['uid'], 'key_' + uid['key'])
#     if not os.path.exists(path):
#         return create_uid()
# 
#     return uid
# 
# def get_user_config_as_json(
#         uid, lastvisit=True, turnpointFiles=True, taskFiles=True,
#         encoded=True):
# 
#     userconfig = read_user_config(uid)
# 
#     json_string = {}
# 
#     json_string['uid'] = uid['uid'] + "." + uid['key']
# 
#     if turnpointFiles:
#         json_string['turnpointFiles'] = {}
# 
#         for key, value in enumerate(userconfig['tp_files']):
#             json_string['turnpointFiles'][key] = {
#                 'filename': value['name'],
#                 'id': (key + 1),
#                 'display': value['display']
#             }
# 
#     if taskFiles:
#         json_string['taskFiles'] = {}
# 
#         for key, value in enumerate(userconfig['task_files']):
#             json_string['taskFiles'][key] = {
#                 'name': value['name'],
#                 'distance': value['distance'],
#                 'type': value['type'],
#                 'turnpoints': value['turnpoints'],
#                 'date': value['date']
#             }
# 
#     if lastvisit:
#         json_string['lastvisit'] = userconfig['lastvisit']
# 
#     if encoded:
#         return json.dumps(json_string, indent=1)
# 
#     return json_string


# Path: prosoar/views/settings.py
from flask import Blueprint, request, jsonify
from geoip import geolite2
from prosoar.userconfig import get_uid_from_cookie, get_user_config_as_json

bp = Blueprint('settings', __name__)


@bp.route('/initial.js')
def initial_js():
    return load(type='js')


@bp.route('/load')
def load(type='json'):
    uid = get_uid_from_cookie()

    type = request.values.get('as', type)

    if type == 'js':
        match = geolite2.lookup(request.remote_addr)

        settings = \
            'var initialSettings = ' + get_user_config_as_json(uid) + ';'

        if match and match.location:
            location = 'var initialLocation = {lon: ' + \
                str(match.location[1]) + ', lat: ' + \
                str(match.location[0]) + '};'
        else:
            location = 'var initialLocation = {lon: 10, lat: 50};'

        return settings + location

    elif type == 'json':

        return jsonify(get_user_config_as_json(uid), encoded=False)