import json

from bottle import request, response

import model
from util import debug


def missing_attributes(attributes):
    for attr in attributes:
        if attr not in request.json:
            return attr
        else:
            return False


def login():
    missing = missing_attributes(['username', 'password'])
    if missing:
        return bad_request('Missing value for attribute ' + str(missing))
    username = request.json['username']
    password = request.json['password']
    session_id = model.login(username, password)
    if session_id:
        return {'session_id': session_id}
    else:
        return forbidden('Invalid login data')


def register():
    missing = missing_attributes(['username', 'password'])
    if missing:
        return bad_request('Missing value for attribute ' + str(missing))
    username = request.json['username']
    password = request.json['password']
    if model.user_exists(username):
        return forbidden('User already exists.')
    if model.register(username, password):
        return {'message': "successfully registered user"}
    else:
        bad_request('registration not successful')


def not_found(msg=''):
    response.status = 404
    if debug:
        msg = str(response.status) + ' Page not found: ' + msg
    response.content_type = 'application/json'
    return json.dumps({"error_message": msg})


def forbidden(msg=''):
    response.status = 403
    if debug:
        msg = str(response.status) + ' Forbidden: ' + msg
    response.content_type = 'application/json'
    return json.dumps({"error_message": msg})


def bad_request(msg=''):
    response.status = 400
    if debug:
        msg = str(response.status) + ' Bad request: ' + msg
    response.content_type = 'application/json'
    return json.dumps({"error_message": msg})