# Copyright 2015 Ian Cordasco
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Module containing the exceptions for the semaphoreci library."""


class SemaphoreCIException(Exception):
    alt_message = None

    def __init__(self, response):
        self.response = response
        try:
            json = response.json()
        except ValueError:  # json library couldn't parse the text
            json = {'error': self.alt_message}

        super(Exception, self).__init__(json['error'])


class NotFound(SemaphoreCIException):
    alt_message = 'Object not found'


class Unauthorized(SemaphoreCIException):
    alt_message = 'Invalid user token'


status_code_to_exception = {
    401: Unauthorized,
    404: NotFound,
}


def raise_for_status(response):
    status_code = response.status_code
    if 400 <= status_code < 600:
        exc_class = status_code_to_exception.get(status_code,
                                                 SemaphoreCIException)
        raise exc_class(response)
