# -*- coding: utf-8 -*-

import flask
from flask import jsonify
from saas.library.python.errorbooster import handle_flask_exception
from werkzeug.exceptions import HTTPException, InternalServerError


class ErrorResponse:
    def __init__(self, status_code, error, description):
        self.status_code = status_code
        self.error = error
        self.description = description

    def as_dict(self):
        return {
            "status": self.status_code,
            "error": self.error,
            "message": self.description
        }

    def get_response(self):
        response = self.as_dict()
        flask.current_app.logger.error(response)
        return response


def forbidden_403(e):
    error = ErrorResponse(403, "Forbidden", "Forbidden error")
    return jsonify(error.get_response()), 403


def unauthorized_401(e):
    error = ErrorResponse(401, "Unauthorized", "Authentication required")
    return jsonify(error.get_response()), 401


def incorrect_args_400(e):
    error = ErrorResponse(400, "Incorrect arguments", "Arguments checking was fault")
    return jsonify(error.get_response()), 400


def validation_error_422(e):
    error = ErrorResponse(422, "Validation error", "Validation was fault")
    return jsonify(error.get_response()), 422


def not_found_404(e):
    if e.description:
        message = e.description
    else:
        message = "Requested object or page was not found"
    error = ErrorResponse(404, "Not found", message)
    return jsonify(error.get_response()), 404


def already_exists_409(e):
    error = ErrorResponse(409, "Already exists", "This object already exists")
    return jsonify(error.get_response()), 409


def unhandled_500(e):
    e = handle_flask_exception(e)
    if isinstance(e, HTTPException):
        message = e.description
    else:
        message = "Something went wrong. Please try again or contact the administrator"
    error = ErrorResponse(500, "Internal server error", message)
    return jsonify(error.get_response()), 500


