from abc import ABC

from ..error import EInvokationError
from ..error import EValidationError


class AbstractApplication(ABC):

    def __init__(self, implementation):
        self.implementation = implementation

    def __call__(self, environ, start_response):
        try:
            status = '200 OK'
            type, body = self.implementation.get_response(environ)
        except EInvokationError as e:
            status = '400 Bad Request'
            type = 'text/plain'
            body = str(e)
        except EValidationError as e:
            status = '422 Unprocessable Entity'
            type = 'text/plain'
            body = str(e)
        except Exception as e:
            status = '500 Internal Server Error'
            type = 'text/plain'
            body = str(e)
        start_response(status, [('Content-Type', type)])
        return [body.encode()]
