# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from flask import jsonify, g

__all__ = [
    'ApiException',
    'handle_api_error',
]


class ApiException(Exception):
    """ Base class for exceptions in Datacloud score API """
    status_code = 500
    code = None

    def __init__(self, request_id=None, stack_trace=None, errors=None):
        super(ApiException, self).__init__()
        self.request_id = request_id or getattr(g, "request_id", None)
        self.errors = errors

    def to_dict(self):
        res = {
            "internal_request_id": self.request_id,
            "code": self.code,
        }
        if self.errors is not None:
            res["errors"] = [
                {
                    "property": prop,
                    "code": code,
                    "message": msg,
                }
                for prop, code, msg in self.errors
            ]
        return res


def handle_api_error(error):
    """ Generates response from ApiException """
    response = jsonify(error.to_dict())
    response.headers['Content-Type'] = 'application/json; charset=utf-8'
    response.status_code = error.status_code
    return response
