import os
import json
from context import PositionalParameterExpectedError, NotFoundError, TypeMismatchError, InvalidValueError, GenericServerError, InvalidRequestMethodError, get_json_value
from server_modules.util import *

def process_request(easydb_context, parameters):
    method = parameters['method']
    if method == 'GET':
        body = process_get_request(easydb_context, parameters)
    elif method == 'POST':
        body = process_post_request(easydb_context, parameters)
    else:
        raise InvalidRequestMethodError(method)
    return {
        'status_code': 200,
        'body': json.dumps(body, indent=4),
        'headers': {
            'Content-Type': 'application/json; charset=utf-8'
        }
    }

def process_get_request(easydb_context, parameters):
    path = parameters['path']
    parts = path.split('/')
    if len(parts) < 2:
        raise PositionalParameterExpectedError('/api/plugin/base/server/error/uuid')
    uuid = parts[1]
    config = easydb_context.get_config()
    errors_dir = get_config(config, 'system/server/directory/server_errors', get_config(config, 'system/server/directory/logfile') + '.errors')
    error_file = '/'.join([errors_dir, uuid, 'error.json'])
    if not os.path.exists(error_file):
        raise NotFoundError('error', uuid)
    with open(error_file, 'r') as f:
        error_json = json.load(f)
    session = easydb_context.get_session()
    try:
        easydb_context.check_system_right('system.server.error.uuid_detail', session)
    except Exception as e:
        cu = get_json_value(session, 'user.user._id')
        eu = get_json_value(error_json, 'session.user.user._id')
        if cu is None or cu != eu:
            raise e
        easydb_context.check_system_right('system.server.error.self_uuid_detail', session)
    return error_json

def process_post_request(easydb_context, parameters):
    path = parameters['path']
    parts = path.split('/')
    if len(parts) < 2:
        raise PositionalParameterExpectedError('/api/plugin/base/server/error/{server|user|api}')
    error_type = parts[1]
    easydb_context.check_system_right('system.root')
    if error_type == 'server':
        raise GenericServerError('something bad happened :(', 'this error was generated by POST /api/plugin/base/server/error/server')
    if error_type == 'user':
        raise NotFoundError('user', '1234')
    if error_type == 'api':
        raise TypeMismatchError('this_is_a_debug_error', 'string')
    raise InvalidValueError('<error_type>', error_type, ['server', 'api', 'user'])

